Way2Java

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();
  }
}


RandomAccessFile rafile = new RandomAccessFile("xyz.txt", "rw");

The RandomAccessFile object rafile opens the file xyz.txt in read write mode. Two modes exist with RandomAccessFile – "r" and "rw".

rafile.getFilePointer()

getFilePointer() of RandomAccessFile returns the file pointer position in the file. When first time read, the method returns 0 as the file pointer is placed at the beginning of the file by the OS when the file opened.

rafile.seek(3*4);

The seek(long) method places the file pointer at the specified position passed as parameter. The seek() method places the file pointer, in the above statement, at the beginning of the 4th integer value (shifts 12 bytes, 3 integer values of 4 bytes each).

Difference between skip() and seek()

The seek() method of RandomAccessFile is equivalent to skip() method of FileInputStream. The small difference is the seek() method counts the bytes always from starting position, that is 0 position known as absolute position. The skip() method counts from relative position (from the existing position) and can accept negative values also. seek() takes always positive values only. Both parameters are of long data type.

For example, seek(100) and seek(200) results in seek(200). skip(100) and skip(200) results in skip(300). skip(300) skips ahead (forward) by 300 bytes from the current position. Suppose the current position of the file pointer is 500 bytes, the skipping results in 800 byte position. Calling skip(-100) moves the file pointer backwards by 100 bytes from current position.

The readInt() method of RandomAccessFile reads an integer value at a time (not byte by byte) and writeInt(int) writes an integer value at atime.

The 7th integer value, originally 30, is overwritten (replaced) with 12345.