Java - Random Access Files

Introduction

Using random access file, you can read from a file as well as write to the file.

Reading and writing using the file input and output streams are a sequential process.

A random access file can read or write at any position.

RandomAccessFile class does the random file access.

You can use it to read/write bytes and all primitive types values to a file.

You can also work with strings using its readUTF() and writeUTF() methods.

RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream classes.

Access Mode

A random access file can be created in four different access modes.

In its constructor, you must specify the access mode.

The access mode value is a string.

Mode Meaning
"r" The file is opened in a read-only mode. You will receive an IOException if you attempt to write to the file.
"rw" The file is opened in a read-write mode. The file is created if it does not exist.
"rws"Same as the "rw" mode, except that any modifications to the file's content and its metadata are written to the storage device immediately.
"rwd"Same as the "rw" mode, except that any modifications to the file's content are written to the storage device immediately.

The following code creates an instance of the RandomAccessFile class by specifying the file name and the access mode.

RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");

A random access file has a file pointer which is a kind of cursor where your next read or write will start.

Its value indicates the distance of the cursor from the beginning of the file in byes.

You can get the value of file pointer by using its getFilePointer() method.

When you create an object of RandomAccessFile class, the file pointer is set to zero.

You can set the file pointer at a specific location in the file using the seek() method.

length() method of a RandomAccessFile returns the current length of the file.

You can extend or truncate a file by using its setLength() method.

The following code shows how to read and write Files Using a RandomAccessFile Object

Demo

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

public class Main {
  public static void main(String[] args) throws IOException {
    String fileName = "randomaccessfile.txt";
    File fileObject = new File(fileName);

    if (!fileObject.exists()) {
      initialWrite(fileName);/*from   w  ww.j  a va 2s .c  o m*/
    }

    // Read the file twice
    readFile(fileName);
    readFile(fileName);
  }

  public static void readFile(String fileName) throws IOException {
    // Open the file in read-write mode
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

    int counter = raf.readInt();
    String msg = raf.readUTF();

    System.out.println("File Read Counter: " + counter);
    System.out.println("File Text: " + msg);
    // Increment the file read counter by 1
    incrementReadCounter(raf);

    raf.close();
  }

  public static void incrementReadCounter(RandomAccessFile raf)
      throws IOException {
    // Read the current file pointer position so that we can restore it at the
    // end
    long currentPosition = raf.getFilePointer();

    // Set the file pointer in the beginning
    raf.seek(0);

    // Read the counter and increment it by 1
    int counter = raf.readInt();
    counter++;

    // Set the file pointer to zero again to overwrite the value of the counter
    raf.seek(0);
    raf.writeInt(counter);

    // Restore the file pointer
    raf.seek(currentPosition);
  }

  public static void initialWrite(String fileName) throws IOException {
    // Open the file in read-write mode
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

    // Write the file read counter as zero
    raf.writeInt(0);

    // Write a message
    raf.writeUTF("Hello world!");
    raf.close();
  }
}

Result