Java-RandomAccessFile

RandomAccessFile

When we read the contents of a file, we normally start at the beginning of the file, read the entire contents until we reach the end of the file. This access pattern is called sequential access. Sometimes, we will like to access specific locations in a file and change the data at just those locations. This access pattern is known as random access. Here, the word “random” means that we can read and modify any byte stored at any location in a file.

The RandomAccessFile class enables us to randomly access any location in a file. We can read and write bytes, characters and primitive data types to any location in a file. This class supports a pointer known as the file pointer. It points to a position in a random access file. The seek( ) method in this class is used to move the file pointer to a desired position. The RandomAccessFile is the only bi-directional stream in Java. A file can be opened for random access for only reading or for both reading and writing by specifying one of the two modes “r” or “rw” in the constructor of the RandomAccessFile class.

Program

new

Program Source

import java.io.RandomAccessFile;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        RandomAccessFile raf = new RandomAccessFile("rand.da","rw");
        raf.writeShort(20);
        raf.writeInt(40);
        raf.writeShort(60);
        raf.writeInt(80);
        raf.seek(0);
        System.out.println(raf.readShort());
        System.out.println(raf.readInt());
        System.out.println(raf.readShort());
        System.out.println(raf.readInt());
        raf.seek(2);
        System.out.println(raf.readInt());
        raf.writeShort(100);
        raf.seek(6);
        System.out.println(raf.readShort());
        System.out.println(raf.readInt());
        raf.close();
    }
}

Leave a Comment