RandomAccessFile
Normally, when reading a file, we read from the beginning toward the end:
But sometimes we want to jump directly to a particular location. This
is called random access.
Java provides RandomAccessFile from java.io. It allows
us to read and write data at any position in a file.
Suppose person.txt contains: Mount Everest
We can move directly to position 3.
import java.io.*;
public class RandomAccessExample {
public static void main(String[] args) {
try {
RandomAccessFile file =
new RandomAccessFile("student.txt", "r");
file.seek(5);//moves the file pointer to byte position 10.
int data = file.read();
System.out.println("Character: " + (char) data);
file.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Other useful methods include:
import java.io.*;
public class RandomAccessExample {
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("student.txt", "r");
System.out.println(file.length());
System.out.println(file.getFilePointer());
file.seek(5);
System.out.println(file.getFilePointer());
file.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
When creating a RandomAccessFile, we specify the mode.
RandomAccessFile file =
new RandomAccessFile("student.txt", "r"); // r means read()
RandomAccessFile file =
new RandomAccessFile("student.txt", "rw");//rw means read and write.