Java Reference
In-Depth Information
You create an instance of the RandomAccessFile class by specifying the file name and the access mode as shown:
RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");
A random access file has a file pointer that is advanced when you read data from it or write data to it. The file
pointer is a kind of cursor where your next read or write will start. Its value indicates the distance of the cursor from
the beginning of the file in byes. You can get the value of file pointer by using its getFilePointer() method. When
you create an object of the RandomAccessFile class, the file pointer is set to zero, which indicates the beginning of the
file. You can set the file pointer at a specific location in the file using the seek() method.
The length() method of a RandomAccessFile returns the current length of the file. You can extend or truncate a
file by using its setLength() method. If you extend a file using this method, the contents of the extended portion of
the file are not defined.
Reading from and writing to a random access file is performed the same way you have been reading/writing
from/to any input and output streams. Listing 7-35 demonstrates the use of a random access file. When you run this
program, it writes two things to a file: the file read counter, which keeps track of how many times a file has been read
using this program, and a text message of “Hello World!”. The program increments the counter value in the file every
time it reads the file. The counter value keeps incrementing when you run this program repeatedly. You may get a
different output every time you run this program.
Listing 7-35. Reading and Writing Files Using a RandomAccessFile Object
// RandomAccessFileReadWrite.java
package com.jdojo.io;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileReadWrite {
public static void main(String[] args) throws IOException {
String fileName = "randomaccessfile.txt";
File fileObject = new File(fileName);
if (!fileObject.exists()) {
initialWrite(fileName);
}
// Read the file twice
readFile(fileName);
readFile(fileName);
}
public static void readFile(String fileName) throws IOException{
// Open the file in read-write mode
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
int counter = raf.readInt();
String msg = raf.readUTF();
System.out.println("File Read Counter: " + counter);
System.out.println("File Text: " + msg);
System.out.println("----------------------------");
Search WWH ::




Custom Search