How to Read/Write from RandomAccessFile in Java

Random access file is a special kind of file in Java which allows non-sequential or random access to any location in the file. This means you don't need to start from 1st line if you want to read line number 10, you can directly go to line 10 and read. It's similar to the array data structure, Just like you can access any element in the array by index you can read any content from the file by using file pointer. A random-access file actually behaves like a large array of bytes stored in the file system and that's why it's very useful for low latency applications which need some kind of persistence e.g. in front office trading application and FIX Engine, you can use random access file to store FIX sequence numbers or all open orders.

This will be handy when you recover from the crash and you need to build your in-memory cache to the state just before the crash.  RandomAccessFile provides you the ability to read and write into any random access file. When you read content from a file, you start with the current location of file pointer, and the pointer is moved forward past how many bytes are read.

Similarly, when you write data into the random access file, it starts writing from the current location of the file pointer and then advances the file pointer past the number of files written. Random access is achieved by setting a file pointer to any arbitrary location using the seek() method.

You can also get the current location by calling getFilePointer() method. There are two main ways to read and write data into RandomAccessFile, either you can use Channel like SeekableByteChannel and ByteBuffer class from Java NIO, this allows you to read data from file to byte buffer or write data from byte buffer to random access file.

Alternatively you can also use various read() and write() method from RandomAccessFile like readBoolean(), readInt(), readLine() or readUTF().  This is a two-part Java IO tutorial, in this part, we will learn how to read and write String from RandomAccess file in Java without using Java NIO channels, and in the next part, we will learn how to read bytes using ByteBuffer and Channel API.

And, If you are new to Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

How to Read/Write into Random Access File

In order to write data into random access file, you first need to create an instance of RandomAccessFile class in read and write mode. You can do this by passing "rw" as mode to the constructor. Once you done that you can either use SeekableByteChannel or seek() method to set the pointer to a location where you want to write data.

You can either writes bytes using ByteBuffer and Java NIO Channel API or you can write int, float, String or any other Java data type by using respective writeInt(), writeFloat() and writeUTF() methods.

All these methods are defined in class in Java IO package. When you write data which exceeds current size of file caused random access file to be extended. For reading data from random access, you can either open the file into read only mode or read write mode.

Just like writing, you can also perform reading either by using Channel API and ByteBuffer class ( you should if you are using Java NIO ) or traditional methods defined in RandomAccessFile in Java. Just like you have different write method to write different data types you also have corresponding read methods to read them back.

In order to read from a random location, you can use seek() method to set the file pointer to a particular location in file. By the way, if end of file is reached before your program read desired number of bytes, an EOFException will be thrown. If any byte cannot be read due to any other reason then IOException will be thrown.

How to read and write from RandomAccessFile in Java

RandomAccessFile Example in Java

Following is our sample Java program to demonstrate how you can you read or write String from a RandomAccessFile. The file name is "" which will be created in current directory, usually in your project directory if you are using Eclipse IDE.

We have two utility method to read String from random access file and write string into file, both method takes an int location to demonstrate random read and random write operation. In order to write and read String, we will be using writeUTF() and readUTF() method, which reads String in modified UTF-8 format.

Though, in this program, I have closed file in try block, you should always do that in a finally block with additional try block, or better use try-with-resource statement from Java 7. I will show you how you can do that in next part of this tutorial when we will learn reading and writing byte arrays using ByteBuffer and SeekableByteChannel class.

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

* Java Program to read and write UTF String on RandomAccessFile in Java.
* @author Javin Paul
public class RandomAccessFileDemo{

    public static void main(String args[]) {

        String data = "KitKat (4.4 - 4.4.2)";
        writeToRandomAccessFile("", 100, data);
        System.out.println("String written into RandomAccessFile
                              from Java Program : " + data);

        String fromFile = readFromRandomAccessFile("", 100);
        System.out.println("String read from RandomAccessFile in Java : "
                               + fromFile);


     * Utility method to read from RandomAccessFile in Java
    public static String readFromRandomAccessFile(String file, int position) {
        String record = null;
        try {
            RandomAccessFile fileStore = new RandomAccessFile(file, "rw");

            // moves file pointer to position specified

            // reading String from RandomAccessFile
            record = fileStore.readUTF();


        } catch (IOException e) {

        return record;

    * Utility method for writing into RandomAccessFile in Java
    public static void writeToRandomAccessFile(String file, int position,
                                 String record) {
        try {
            RandomAccessFile fileStore = new RandomAccessFile(file, "rw");

            // moves file pointer to position specified

            // writing String to RandomAccessFile


        } catch (IOException e) {

String written into RandomAccessFile from Java Program : KitKat (4.4 - 4.4.2)
String read from RandomAccessFile in Java : KitKat (4.4 - 4.4.2)

That's all about how to read and write from RandomAccessFile in Java.  You would be surprised that this class is available from JDK 1.0 itself.  It is indeed a very useful class from traditional Java IO API, which was the only source of doing high-speed IO before Java NIO came with memory-mapped file.

If you like this Java IO tutorial and hungry for more checkout following tutorials :
  • How to read/write XML file in Java using DOM Parser? (program)
  • How to read a text file in Java? (solution)
  • How to check if a file is hidden in Java? (tutorial)
  • How to make JAR file in Java? (steps)
  • How to read Properties file in Java? (program)
  • How to create File and Directory in Java? (solution)
  • How to read File line by line using BufferedReader in Java? (solution)
  • How to write JSON String to file in Java? (solution)
  • How to change File permissions in Java? (program)
  • How to append text to a file in Java? (example)
  • How to parse XML step by step using SAX Parser? (solution)
  • How to copy File in Java? (program)
  • How to upload File in Java web application using Servlets? (demo)
  • Difference between getPath(), getAbsolutePath() and getRelativePath()? (difference)

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

No comments :

Post a Comment