Using RandomAccessFile class

In this section, we will learn about the RandomAccessFile class provided by the java.io package. This is a class that allows us to read and write arbitrary bytes, text, and primitive Java data types from or to any specified location in a file. As the name suggests, random that means it is not sequential and the data can be read from and written to any specified position in the file. 

Mostly, Users use the input stream or output stream in a sequential but unlike the input and output streams java.io.RandomAccessFile is used for both reading and writing files. A random access file treats with a large array of bytes stored in the file system and uses the file pointer to deal with the index of that array. This file pointer points the positions in the file where the reading or writing operation has to be done.

RandomAccessFile class implements the same interfaces as the DataInputStream and the DataOutputStream. Thus it defines the same methods for reading and writing data to a file. 

 

This program shows the implementation of the RandomAccessFile class. The first  part of the program takes an input from user to the name of a file and  checks if it exists then it writes the specified string using the method writeChars(). Otherwise it displays the appropriate message as “File does not exist”.  An IOException may be thrown if the stream has been closed. 

There are following methods has been used in this program:

RandomAccessFile rand = new RandomAccessFile(file,"rw");

The above code snippet creates an instance of the RandomAccessFile class mentioning the mode in which file has to be opened. The constructor RandomAccessFile( ) takes two arguments: First is the file name and another is the operation mode (read-write mode). We are opening the file into read and write mode (“rw”).

 

There are following methods that are used in the given program (FileTest14.java) shown as—

rand.seek(file.length()): This is the seek( ) method of the RandomAccessFile class has been used to jump the file position at the specified. Here, using file.length() returns to the end of the file.

rand.close(): This is the close( ) method of the RandomAccessFile class has been used to close the created the instance of the RandomAccessFile class.

writeBytes( ): This the writeBytes( ) method which simply writes the content into the file. This method always append the file content with our specified text.

readByte(): The second part of the program reads the characters from a file using the readByte() method.

 

Here is the code of the program:

FileTest14.java

import java.io.*;

public class FileTest14 {

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
RandomAccessFile rand = null;

if (!file.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}

//Open the file for both reading and writing
try {
rand = new RandomAccessFile(file, "rw");
rand.seek(file.length()); //Seek to end of file
rand.writeBytes("Its Good Bye from Me."); //Write end of file
System.out.println("Written Successfully!");
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
rand.close();
}

//Open the file for reading only
try {
rand = new RandomAccessFile(file, "r");
int n = (int) rand.length();
System.out.println("Length: " + n);
rand.seek(0); //Seek to start point of file

System.out.println("\nFile Contents:~ ");
for (int i = 0; i < n; i++) {
byte b = rand.readByte(); //read byte from the file
System.out.print((char) b); //convert byte into char
}
System.out.println();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
rand.close();
}

}

}

 

The output is shown here:

C:\file>java FileTest14
Enter File name : new.txt
Written Successfully!
Length: 76

File Contents:~
It's Merry Christmas..
Enjoy this festive season..
Its Good Bye from Me.

 

Note:

The initial contents of the file “new.txt” was-

It’s Merry Christmas..
Enjoy this festive season..