Saturday, September 18, 2021

How to Read/Write from RandomAccessFile in Java - Example Tutorial

Random access file is a special kind of file in Java that 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 a 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 the 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 the 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 the 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 reading and write mode. You can do this by passing "rw" as the mode to the constructor. Once you have 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 write 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 java.io.RandomAccessFile class in the Java IO package. When you write data that exceeds the current size of the file caused random access file to be extended. For reading data from random access, you can either open the file into the 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 methods 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 the file. By the way, if the end of the file is reached before your program reads the 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 read or write String from a RandomAccessFile. The file name is "sample.store" which will be created in the current directory, usually in your project directory if you are using Eclipse IDE.

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


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


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
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("sample.store", 100, data);
        System.out.println("String written into RandomAccessFile
                              from Java Program : " + data);

        String fromFile = readFromRandomAccessFile("sample.store", 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
            fileStore.seek(position);

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

            fileStore.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        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
            fileStore.seek(position);

            // writing String to RandomAccessFile
            fileStore.writeUTF(record);

            fileStore.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



Output:
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 the memory-mapped file.

If you like this Java IO tutorial and are hungry for more checkout following tutorials :
  • How to read/write XML files 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 a 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 Files in Java? (program)
  • How to Upload File in Java web application using Servlets? (demo)
  • Difference between getPath(), getAbsolutePath() and getRelativePath()? (difference)

Thanks for reading this Java RandomAccess tutorial so far. If you like this Java NIO tutorial and example then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note. 

No comments :

Post a Comment