Java IO: RandomAccessFile

Connect with me:  
  Jenkov.com - News

The RandomAccessFile class in the Java IO API allows you to move around a file and read from it or write to it as you please. You can replace existing parts of a file too. This is not possible with the FileInputStream or FileOutputStream.


Creating a RandomAccessFile

Before you can work with the RandomAccessFile class you must instantiate it. Here is how that looks:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

Notice the second input parameter to the constructor: "rw". This is the mode you want to open file in. "rw" means read/write mode. Check the JavaDoc for more details about what modes you can open a RandomAccessFile in.


Moving Around a RandomAccessFile

To read or write at a specific location in a RandomAccessFile you must first position the file pointer at the location to read or write. This is done using the seek() method. The current position of the file pointer can be obtained by calling the getFilePointer() method.

Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.seek(200);

long pointer = file.getFilePointer();

file.close();

Reading from a RandomAccessFile

Reading from a RandomAccessFile is done using one of its many read() methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

int aByte = file.read();

file.close();

The read() method reads the byte located a the position in the file currently pointed to by the file pointer in the RandomAccessFile instance.

Here is a thing the JavaDoc forgets to mention: The read() method increments the file pointer to point to the next byte in the file after the byte just read! This means that you can continue to call read() without having to manually move the file pointer.


Writing to a RandomAccessFile

Writing to a RandomAccessFile can be done using one it its many write() methods. Here is a simple example:

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.write("Hello World".getBytes());

file.close();

Just like with the read() method the write() method advances the file pointer after being called. That way you don't have to constantly move the file pointer to write data to a new location in the file.


RandomAccessFile Exception Handling

The proper exception handling of a RandomAccessFile is left out of this text for clarity. However, a RandomAccessFile must be closed properly after use, just like with a stream or reader / writer. To lean more, see the text Java IO Exception Handling.

Connect with me:
     
Newsletter - Get all my free tips!