Java supports a file reading writing mechanism which is allows us to manipulate data at any specific location of the file. A random access file works like an array of bytes. It do not create an array in the memory. It just treat file as a byte array and maintain the current index of the same. So that we can read or write from the specific location that is also called as file pointer. There are various ways to create an object of java.io.RandomAccessFile class. If the object is created in read/write mode, then write operations are also allowed. The file pointer can be read by the getFilePointer method and set by the seek method.

Important Points:

  • RandomAccessFile manages a file pointer
  • On creating the object, It points to the 1st byte of the file
  • On trying to skip bytes which are even more than the file size, it will reach to end of the file.

Constructor Summary

public RandomAccessFile (File file, String mode) throws FileNotFoundException
public RandomAccessFile (String filePath, String mode) throws FileNotFoundException

RandomAccessFile Modes

"r"	  Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.
"rw"  Open for reading and writing. If the file does not already exist then an attempt will be made to create it.
"rws" Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.
"rwd" Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.

Program:

Aim: Write a program using RandomAccessFile class to write 4 int values in a file. Access the 3rd int from the file and change its value by another.

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

public class RandomAccessDemo 
{
  public static void main(String[] args) 
  {
    try 
	{		
      RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
      raf.writeInt(10);
      raf.writeInt(20);
      raf.writeInt(30);
      raf.writeInt(400);

      raf.seek((3 - 1) * 4);  // For 3rd integer, We are doing 2 * size of Int(4).

      raf.writeInt(99);

      raf.seek(0);   // Going back to start point
      
      int i = 0;
      while(raf.length()>raf.getFilePointer()) 
      {
		i = raf.readInt();
        System.out.println(i);
      }
      raf.close();
    } 
	catch (Exception e) 
	{
		System.out.println(e);
    }
  }
}

Output:
Random Access File example


Aim: Write a program using RandomAccessFile class to append an existing file (Generated by above program).

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

public class RAFAppendDemo 
{
  public static void main(String[] args) throws Exception 
  {
    File f = new File("test.txt");
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);
    raf.writeBytes("Appended text\n");
  
    raf.seek(0);
	
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readLine());  
  
    raf.close();
  
  }
  
}

Output:
Random Access File