Middle
What do you know about the RandomAccessFile class?
sobes.tech AI
Answer from AI
RandomAccessFile provides the ability to read and write data at any location in a file. Unlike streams, it is not a subclass of InputStream or OutputStream.
Key features:
- Positioning: Allows moving within the file, setting the current position using the
seek()method. - Access modes: Opened with a specific access mode (
"r","rw","rws","rwd"). - Read and write: Supports reading and writing primitive data types, strings, and byte arrays.
- File length: Can get the current file length (
length()) and set it (setLength()).
Example of opening a file for reading and writing:
// RandomAccessFile
RandomAccessFile file = new RandomAccessFile("my_file.txt", "rw");
// ... work with the file
file.close();
Example of moving within a file and reading:
// RandomAccessFile
RandomAccessFile file = new RandomAccessFile("my_file.bin", "r");
file.seek(100); // Move to the 100th byte
byte b = file.readByte(); // Read one byte
file.close();
Example of writing to a file:
// RandomAccessFile
RandomAccessFile file = new RandomAccessFile("my_output.txt", "rw");
file.writeBytes("Hello, world!"); // Write string
file.close();
Access modes:
| Mode | Description |
|---|---|
"r" |
Open for reading. |
"rw" |
Open for reading and writing. |
"rws" |
Open for reading and writing with synchronous update of content and metadata at OS level. |
"rwd" |
Open for reading and writing with synchronous content update at OS level (metadata may be delayed). |