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 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 array data structure, Just like you can access any element in array by index you can read any content from file by using file pointer. A random access file actually behaves like a large array of bytes stored in file system and that's why its very useful for low latency applications which needs 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 crash and you need to build your in memory cache to the state just before the crash.  RandomAccessFile provides you ability to read and write into any random access file. When you read content from file, you start with current location of file pointer and pointer is moved forward past how many bytes are read. Similarly when you write data into random access file, it starts writing from current location of file pointer and then advances the file pointer past number of files written. Random access is achieved by setting file pointer to any arbitrary location using seek() method. You can also get current location by calling getFilePointer() method. There are two main ways to read and write data into RandomAccessFile, either you can use Channel e.g. 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 e.g 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 next part we will learn how to read bytes using ByteBuffer and Channel API. .




How to Read/Write into Random Access File

How to read and write from RandomAccessFile in Java
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 java.io.RandomAccessFile 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.



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 "sample.store" 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.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 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 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)


No comments :

Post a Comment