Java Random Access Files
The RandomAccessFile
class in Java allows you to read from and write to a file at any position. It supports both sequential and random access, making it suitable for tasks like updating records in a file.
1. Creating a RandomAccessFile
Instantiate a RandomAccessFile
object by specifying the file and the mode ("r"
for read-only, "rw"
for read and write).
Example:
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
RandomAccessFile raf = new RandomAccessFile("data.txt", "rw");
// Use raf to read and write
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Reading Data
You can read data using methods like readInt()
, readLine()
, readUTF()
, etc.
Example: Reading from a Specific Position
raf.seek(100); // Move the file pointer to position 100
int data = raf.readInt();
3. Writing Data
Write data using methods like writeInt()
, writeUTF()
, etc.
Example: Writing at a Specific Position
raf.seek(200); // Move the file pointer to position 200
raf.writeUTF("Hello, World!");
4. Getting the File Pointer
You can get the current position of the file pointer using getFilePointer()
.
Example:
long position = raf.getFilePointer();
System.out.println("Current file pointer position: " + position);
5. Key Takeaways
RandomAccessFile
allows reading and writing at arbitrary positions.- Supports both sequential and random access.
- Useful for applications like databases and file-based records.
- Always close the file to release resources.
- Be mindful of data types and file formats when using random access.