RandomAccessFile Read Sequentially Randomly

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".


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.


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.

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.