RandomAccessFile Read Sequentially Randomly

A file can be read either sequentially (continuously) or randomly (here and there). So far, in all the programs, what we have done is sequential access, starting from the beginning of the file to the end of the file. Or we have skipped some bytes in a file and read the remaining bytes of the file with skip() method. In random access, the file pointer is taken to a specific byte and that byte is read or modified. To support random access (to read and write at any position in a file), there comes special class – java.io.RandomAccessFile.

Random access is very much required in quick accessing the data randomly as in the case of super bazaar billing, help desk in a bank or railways and airline reservations etc. These types of programs where quick response is required are known as mission critical operations.

The java.io.RandomAccessFile is very special as it contains unique features that other I/O streams do not.

  1. It is not a subclass of InputStream or OutputStream. It is a direct subclass of Object class, but placed in java.io package.
  2. It neighter an input stream nor output stream as it can do both the jobs of reading and writing. For this reason, while opening the file with RandomAccessFile class, we must specify the mode – read mode or write mode.
  3. It can read or write a file both sequentially and randomly.
  4. It includes the methods for reading and writing. All the methods of DataInputStream class and DataOutputStream classes are available in RandomAccessFile (as it implements both DataInput and DataOutput interfaces) like readInt(), writeInt(), readDouble() and writeDouble() etc.

Following is the class signature

public class RandomAccessFile extends Object implements DataOutput, DataInput

The two important modes supported byRandomAccessFile are "r" and "rw".

Reading randomly with RandomAccessFile

In the following program, a file, xyz.txt is opened which is initially empty. In a for loop, 10 integer values are written sequentially and then also read sequentially. Later, the file pointer is taken to a specific integer value and then the value is read and later also modified.

The file operations done with RandomAccessFile in the program are:

  1. 10 integer values are written sequentially (all one after another)
  2. 10 integer values written earlier are read sequentially (all one after another)
  3. To read 4th integer value by accessing randomly
  4. To modify 7th integer value by accessing randomly
import java.io.*;
public class RAFDemo
{
  public static void main(String args[]) throws IOException
  {                     				         
    RandomAccessFile rafile = new RandomAccessFile("xyz.txt", "rw");
		// writing 10 integer values sequentially one after another
    for(int i = 0; i < 10; i++)
    {
      rafile.writeInt(i*5);
    }
    	     // to know the file pointer position in the file
    System.out.println("File pointer position before skipping: " + rafile.getFilePointer());

	 // to shift the file pointer to 0 (starting) position to read from beginning
    rafile.seek(0);
    System.out.println("File pointer position after skipping: " + rafile.getFilePointer());            

    System.out.println("Reading sequentially one after another:");
    for(int i = 0; i < 10; i++)
    {
      System.out.println(rafile.readInt());
    }
           			// to read randomly 4th integer value
    rafile.seek(3*4);  // 3 integer values of size 4 bytes each
    System.out.println("4th integer value reading randomly: " + rafile.readInt());

			      // to change randomly the 7th intger value
    rafile.seek(6*4); // 6 integer values of size 4 bytes each

    rafile.writeInt(12345); 	
                             // to read and print again sequentially
    rafile.seek(0);  // again place the file pointer at the start
    System.out.println("\nValues after modification of 7th integer value randomly");
    for(int i = 0; i < 10; i++)
    {
      System.out.println(rafile.readInt());
    }
    rafile.close();
  }
}


3 thoughts on “RandomAccessFile Read Sequentially Randomly”

  1. Sir, when i open the file xyz.txt from hard disk i can’t see the integers which i have write. The xyz.txt display different type of symbol which i can’t understand. so how to see the write integers in the file xyz.txt .

  2. Sir you had written “seek(100) and seek(200) results in seek(200)” what is this meaning seek() method places the cursor in 200th position aa?? if it is then why u placed two seek() methods here

Leave a Comment

Your email address will not be published.