📜  Java RandomAccessFile(1)

📅  最后修改于: 2023-12-03 15:01:31.922000             🧑  作者: Mango

Java RandomAccessFile

The Java RandomAccessFile class is a file handling class present in the java.io package. It provides methods for both reading and writing data to a file. It differs from other file handling classes like FileInputStream and FileOutputStream by allowing both read and write operations at any position within the file.

Initialization

To create a RandomAccessFile object, you can use one of the following constructors:

RandomAccessFile file = new RandomAccessFile(String fileName, String mode);
RandomAccessFile file = new RandomAccessFile(File fileObj, String mode);
  • fileName specifies the file name or path as a String object.
  • fileObj specifies the File object representing the file.
  • mode can be either "r" for read-only mode, "rw" for read and write mode, "rwd" for read and write mode with synchronous disk updates, or "rws" for read and write mode with synchronous disk updates.
Reading Operations

The RandomAccessFile class provides various methods to read data from a file. Some of the commonly used methods are:

  • int read(): Reads a byte of data from the file and returns it as an integer. Returns -1 if the end of the file is reached.
  • int read(byte[] buffer): Reads up to buffer.length bytes of data from the file into the specified byte array.
  • int read(byte[] buffer, int offset, int length): Reads up to length bytes of data from the file into the specified byte array, starting from the given offset.
Writing Operations

The RandomAccessFile class also provides methods to write data to a file. Some of the commonly used methods include:

  • void write(int value): Writes a byte of data to the file.
  • void write(byte[] buffer): Writes the entire byte array to the file.
  • void write(byte[] buffer, int offset, int length): Writes a portion of the byte array to the file.
File Pointer Manipulation

The RandomAccessFile class allows you to manipulate the file pointer, which determines the position where data is read from or written to within the file. The following methods are used to move the file pointer:

  • long getFilePointer(): Returns the current position of the file pointer.
  • void seek(long position): Sets the file pointer to the specified position.
  • long length(): Returns the length of the file in bytes.
Example

Here's a simple example that demonstrates reading and writing data using RandomAccessFile:

import java.io.*;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("file.txt", "rw");

            // Writing data to the file
            file.writeUTF("Hello, World!");
            file.writeInt(100);
            file.writeBoolean(true);

            // Moving the file pointer
            file.seek(0);

            // Reading data from the file
            String str = file.readUTF();
            int num = file.readInt();
            boolean flag = file.readBoolean();

            System.out.println("String: " + str);
            System.out.println("Number: " + num);
            System.out.println("Flag: " + flag);

            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a RandomAccessFile object with the file name "file.txt" and mode "rw". We write a string, an integer, and a boolean value to the file, and then read them back using the appropriate methods. Finally, we close the file using the close() method.

Remember to handle the IOException when working with RandomAccessFile as it can throw exceptions related to file handling operations.

Conclusion

The RandomAccessFile class in Java provides a convenient way to perform read and write operations at any position within a file. It offers flexibility and control over file handling tasks, making it a powerful tool for programmers dealing with file manipulation.