Read and write files using the Random AccessFile class

1. Introduction to Random AccessFile class

The first essay< File class traverses directories and files > It has been said that File classes can only be used to represent the name, size and other information of a file or directory, but not to access the contents of a file. When you need to access the file content, you can use the Random AccessFile class.

_Random Access File is a class provided by Java to access files that store data records. It can read or write data. The data written is stored in byte form. It supports random access, that is, it can access any location of the file (through file pointer).

2. Constructor

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

The two constructors are very similar in usage. Name and file are used to specify the path and name of the open file, while mode is used to specify the way to open the file. The commonly used parameters are two "r" and "rw", which are read-only and read-write.

When the file is opened, the file pointer points to the beginning of the file, that is pointer=0, which can be viewed by the getFilePointer() method of Random AccessFile.

Example: Create and open a data file.

//Create directories
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();
}
//Instantiate Random AccessFile object
RandomAccessFile raf = new RandomAccessFile(file, "rw");
//When opening a file, the pointer is at the top, that is, 0
System.out.println(raf.getFilePointer());

3. Write operation

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

In the third method, off is the initial index value of the data to be written in array b, while len is the length to be written. The write method writes one byte at a time, and if the data written exceeds one byte, it writes the last eight bits. Binary Operational Basis).

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

Example: Write an integer to a file through the write() method. (Objects created following the example above)

//The write() method inserts only one byte at a time, and more than one byte is written to the last eight bits, so writing an integer requires four times.
int num = 28;
raf.write(num >>> 24);
raf.write(num >>> 16);
raf.write(num >>> 8);
raf.write(num);

Of course, the Random AccessFile class also provides a simpler method, writeXxx(), which can directly write Int (i) if an integer is inserted, and writeBoolean() if boolean, and so on. But it should be clear that these methods are still implemented through the above write() method.

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

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

4. Read operation

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

Similar to the write operation, the read operation is implemented by the read() method, which reads one byte at a time, and the file pointer points to the next location (by seeking () method to move the pointer to the read position). At the same time, Random AccessFile class also encapsulates readXxx() series of methods for easy reading, the principle and use of which can refer to write operations, basically similar.

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

//To read a file, you need to move the file pointer to the front through the seek() method before reading it.
raf.seek(0);
for (int i = 0; i*4 < raf.length(); i++) {
    System.out.println(raf.readInt());
}

5. Close files

_Open files must be closed through close(), otherwise unexpected errors may occur.

6. Complete examples

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

public class MyRandomAccessFile {

    public static void main(String[] args) throws IOException {
        //Create directories
        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();
        }
        
        //Instantiate Random AccessFile object
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        //When opening a file, the pointer is at the top, that is, 0
        System.out.println(raf.getFilePointer());

        //Write data
        int[] num = {28, 14, 56, 23, 98};
        for (int i : num) {
            raf.writeInt(i);
        }
        
        //To read a file, you need to move the file pointer to the front through the seek() method before reading it.
        raf.seek(0);
        for (int i = 0; i*4 < raf.length(); i++) {
            System.out.println(raf.readInt());
        }
        
        //Close the file after the operation.
        raf.close();
    }
}

Keywords: Java

Added by marijn on Mon, 08 Jul 2019 20:43:29 +0300