Java USES the RandomAccessFile class to read and write files

  • 2020-07-21 07:41:09
  • OfStack

1. Introduction to RandomAccessFile Class

As mentioned in the previous article, File Class Traverses Directories and Files, File class can only be used to represent the name, size and other information of a file or directory, and cannot be used to access the contents of a file. When you need to access the contents of a file, you can use the RandomAccessFile class.

RandomAccessFile is a class provided by Java to access 1 files that hold data records. It can be read or written, and the written data is stored in the form of byte. Support for random access, that is, you can access the file anywhere (through the file pointer).

2. Constructor


RandomAccessFile(String name, String mode)
RandomAccessFile(File file, String mode)

The constructor usage is very similar, name and file are used to specify the path and name of the file to open, and mode is used to specify how to open the file. The common arguments are "r" and "rw", which are read only and read write.

After the file is opened, the file pointer points to the beginning of the file, which is pointer=0, and can be viewed through the getFilePointer() method of RandomAccessFile.

Example: Create and open a data file.


// Create a directory 
File dir = new File("demo");
if (!dir.exists()) {
  dir.mkdir();
}
// Create a file 
File file = new File(dir, "test.dat");
if (!file.exists()) {
  file.createNewFile();
}
// instantiation RandomAccessFile object 
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// When the file is opened, the pointer position is at the front, i.e 0
System.out.println(raf.getFilePointer());

3. Write


write(int i)
write(byte[] b)
write(byte[] b, int off, int len)

The third method, off, is the starting index of the data to be written in the array b, and len is the length to be written. The write method writes one byte at a time, and if more than one byte is written, the last eight bits are written (see: base 2 arithmetic basics if you don't understand it here).

In addition, for every byte written, the file pointer points to the next byte.

Example: Writes an integer to a file using the write() method. (Follow the object created in the example above)


//write() Method inserts only at a time 1 Three bytes. Greater than 1 Two bytes is written 8 Bit, so write 1 An integer number needs to be written 4 time 
int num = 28;
raf.write(num >>> 24);
raf.write(num >>> 16);
raf.write(num >>> 8);
raf.write(num);

Of course, the RandomAccessFile class also provides an easier method, writeXxx(). If you insert an integer, you can directly use writeInt(i). , writeBoolean(), and so on. It should be clear, however, that these methods are implemented using the write() method above.

Example: The following is the body of the writeInt() method in the RandomAccessFile class.


public final void writeInt(int v) throws IOException {
  write((v >>> 24) & xFF);
  write((v >>> 16) & xFF);
  write((v >>> 8) & xFF);
  write((v >>> 0) & xFF);
  //written += 4;
}

4. Read operation


read(int i)
read(byte[] b)
read(byte[] b, int off, int len)

Like the write operation, the read operation is implemented through the read() method, which reads one byte at a time while the file pointer points to the next position (the seek() method moves the pointer to the read position). At the same time, the RandomAccessFile class also encapsulates the readXxx() series of methods for easy reading, the principle and use method can refer to the write operation, basically similar.

Example: Reads all data in the data file as an integer.


// Read the file, need to pass before reading seek() Method moves the file pointer to the front 
raf.seek(0);
for (int i = 0; i*4 < raf.length(); i++) {
  System.out.println(raf.readInt());
}

Close the file

Open file 1 must be closed via close(), otherwise unexpected errors may occur.

6. Complete example


import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MyRandomAccessFile {

  public static void main(String[] args) throws IOException {
    // Create a directory 
    File dir = new File("demo");
    if (!dir.exists()) {
      dir.mkdir();
    }
    // Create a file 
    File file = new File(dir, "test.dat");
    if (!file.exists()) {
      file.createNewFile();
    }
    
    // instantiation RandomAccessFile object 
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    // When the file is opened, the pointer position is at the front, i.e 0
    System.out.println(raf.getFilePointer());

    // Write data 
    int[] num = {28, 14, 56, 23, 98};
    for (int i : num) {
      raf.writeInt(i);
    }
    
    // Read the file, need to pass before reading seek() Method moves the file pointer to the front 
    raf.seek(0);
    for (int i = 0; i*4 < raf.length(); i++) {
      System.out.println(raf.readInt());
    }
    
    // After operation 1 Make sure you close the file 
    raf.close();
  }
}

Related articles: