Java RandomAccessFile

Jakob Jenkov
Last update: 2019-12-04

The Java RandomAccessFile class in the Java IO API allows you to move navigate 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. The different access modes supported by the Java RandomAccessFile is covered in the next section.

Access Modes

The Java RandomAccessFile supports the following access modes:

ModeDescription
rRead mode. Calling write methods will result in an IOException.
rwRead and write mode.
rwdRead and write mode - synchronously. All updates to file content is written to the disk synchronously.
rwsRead and write mode - synchronously. All updates to file content or meta data is written to the disk synchronously.

Seeking in a RandomAccessFile

To read or write at a specific location in a RandomAccessFile you must first position the file pointer at (AKA seek) the position to read or write. This is done using the seek() method. Here is an example of seeking to a specific position in a Java RandomAccessFile:

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

file.seek(200);

Get File Position

You can obtain the current position of a Java RandomAccessFile using its getFilePointer() method. The current position is the index (offset) of the byte that the RandomAccessFile is currently positioned at. Here is an example of obtaining the current position of a RandomAccessFile using its getFilePointer() method:

long position = file.getFilePointer();

Read Byte from a RandomAccessFile

Reading a byte from a Java RandomAccessFile is done using its read() method. Here is a simple example of reading data from a RandomAccessFile:

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

int aByte = file.read();

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.

Read Array of Bytes from a RandomAccessFile

It is also possible to read an array of bytes from a Java RandomAccessFile. Here is an example of reading an array of bytes from a RandomAccessFile:

RandomAccessFile randomAccessFile = new RandomAccessFile("data/data.txt", "r");

byte[] dest      = new byte[1024];
int    offset    = 0;
int    length    = 1024;
int    bytesRead = randomAccessFile.read(dest, offset, length);

This example reads a sequence of bytes into the dest byte array passed as parameter to the read() method. The read() method will start reading in the file from the current file position of the RandomAccessFile. The read() method will start writing data into the byte array starting from the array position provided by the offset parameter, and at most the number of bytes provided by the length parameter. This read() method returns the actual number of bytes read.

Write Byte to a RandomAccessFile

You can write a single byte to a RandomAccessFile using its write() method which takes an int as parameter. The byte will be written to the current file position of the RandomAccessFile. The previous byte at that position will be overwritten. Here is an example of writing a single byte to a Java RandomAccessFile:

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

file.write(65); // ASCII code for A

Remember, calling this write() method will advance the file position of the RandomAccessFile by 1.

Write Array of Bytes 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");

byte[] bytes = "Hello World".getBytes("UTF-8");

file.write(bytes);

This example writes the array of bytes to the current file position of the RandomAccessFile. Any bytes currently at this position will be overwritten with the new bytes.

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.

You can also write parts of a byte array to a RandomAccessFile, instead of all of the byte array. Here is an example of writing part of a byte array to a Java RandomAccessFile:

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

byte[] bytes = "Hello World".getBytes("UTF-8");

file.write(bytes, 2, 5);

This example writes from offset 2 of the byte array and 5 bytes forward, to the RandomAccessFile.

close()

The RandomAccessFile has a close() method which must be called when you are done using the RandomAccessFile instance. You can see example of calls to close() in the examples above. Here is an example of closing a Java RandomAccessFile:

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

file.close();

You can also close a RandomAccessFile automatically, if you use the Java Try With Resources construct. Here is an example of closing a RandomAccessFile automatically using the Java try-with-resources construct:

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

    //read or write from the RandomAccessFile

}

Once the program execution exits the try-with-resources block above, the RandomAccessFile will automatically be closed, even if an IOException is thrown from inside the try-with-resources block.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next