RandomAccessFile Read Sequentially Randomly

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

2 thoughts on “RandomAccessFile Read Sequentially Randomly

Leave a Reply

Your email address will not be published. Required fields are marked *