Java RandomAccessFile explanation with examples

Introduction :

RandomAccessFile is an important class in the Java IO package. Using this class, we can easily point to any position of a file, read any specific part of a file or write content to anywhere within a file. It behaves like a large array of bytes. The cursor, that is used to point to the current position of a file is called file pointer.
For random access file, we can open a file in ‘read mode’ (‘r’), read-write mode (‘rw’), ‘rws’ and ‘rwd’ mode. ‘rws’ will open a file in read-write mode and also require that every update to the file’s content or metadata be written synchronously to the underlying device. Similarly, ‘rwd’ requires every update to the file’s content is written synchronously to the underlying storage device.
In this tutorial, we will learn different usage of RandomAccessFile with examples. Let’s have a look :

How to use RandomAccessFile :

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

public class Main {
    private static final String PATH = "C:\\user\\Desktop\\file.txt";

    public static void main(String[] args) {
        try {
            //1
            RandomAccessFile raFile = new RandomAccessFile(PATH, "r");

            //2
            raFile.seek(0);
            byte[] bytes = new byte[4];

            //3
            raFile.read(bytes);
            System.out.println(new String(bytes));

            //4
            raFile.seek(10);
            raFile.read(bytes);
            raFile.close();

            System.out.println(new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Java RandomAccessFile Example

Explanation:

The commented numbers in the above program denote the step number below:

1. First of all, we have created one RandomAccessFile variable for the file defined by PATH i.e. file.txt. This file contains the following text:

This is a file with few random words.Hello World!Hello Universe!Hello again!Welcome!

The created file is in read-only mode‘r’.
2. First of all, we need to position the file pointer to the position where we want to read or write. seek() method is used for it. In our example, we have moved it to the 0th position,i.e.to the first position. Then we have created one byte array. The size of this array is 4.
3. Using read() method, we have read the content of the file starting from 0th position. It will read it and put the content in the byte array bytes. It will read the same amount of content as the size of bytes array. Next, convert the content of bytes to a String and print out the result.
4. Similar to the above example, we have moved to10th position, read the content and stored it in a byte array and print out the content. The output of both print lines will be as below:

 This
 file

So, the first println printed out the first word This, and the second one printed out file, This is starting from the 0th position and file is starting from te 10th position. Both have letters.

Writing content to a file:

Writing content to a file is similar to reading. The method looks like as below:

      try{
         //1
         RandomAccessFile raFile=new RandomAccessFile(PATH,"rw");

         //2
         raFile.seek(4);
         raFile.write("Hello".getBytes());
         raFile.close();

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

Java RandomAccessFile Example

1. File creation is similar to the previous example. The only difference is that we are opening it in ‘rw’ or read-write mode.
2. For writing content, write() method is used. One byte array is passed to this method and it will write down the content of this array. The write operation starts from the current pointer position. In our case, we have moved the pointer to4thposition using seek() , so it will start writing from the4thposition of the file.

The content of the text file will look like as below:

ThisHello file with few random words.Hello World!Hello Universe!Hello again!Welcome!

So, the content is overridden after the write operation.

Getting the size of a file:

We can get the size or length of a file using the length() method. It will return the size of the file:

      try{
         RandomAccessFile raFile=new RandomAccessFile(PATH,"r");

         System.out.println("length of the file is "+raFile.length());
         }catch(IOException e){
         e.printStackTrace();
         }

So, we can append a text to the end of a file by seeking the pointer to the last position of a file first :

public static void main(String[] args) {
        try{
            RandomAccessFile raFile=new RandomAccessFile(PATH,"rw");

            raFile.seek(raFile.length());
            raFile.write("Hello".getBytes());
            raFile.close();

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

    }

Java RandomAccessFile Example

Setting a new length to a file :

We can also change the length of a file using setLength(long newLength) method. It will change the length of the size to newLength. If the new length size is smaller than the previous length, it will truncate the content of the file. Else, the file size will be increased. For example :

  public static void main(String[] args) {
        try{
            RandomAccessFile raFile=new RandomAccessFile(PATH,"rw");
            System.out.println("File length "+raFile.length());

            raFile.setLength(3);

            System.out.println("File length after setting : "+raFile.length());

            raFile.close();

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

Java RandomAccessFile Example

If our input file contains the word Hello, it will print out the following output :

File length 5
File length after setting the length 3

i.e. the length of the file was 5 previously but after changing the length, it becomes 3. If you open it, you can see that it contains only word Hel.

Get the current pointer position :

For reading the current pointer position, i.e. on which position it is pointed to, we can use getFilePointer() method. It returns the position in long format.

    public static void main(String[] args) {
        try{
            RandomAccessFile raFile=new RandomAccessFile(PATH,"r");

            System.out.println("Current file pointer position 1 : "+raFile.getFilePointer());
            raFile.seek(3);
            System.out.println("Current file pointer position 2 : "+raFile.getFilePointer());
            raFile.close();

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

Java RandomAccessFile Example

The output will be like below :

Current file pointer position 1 : 0
Current file pointer position 2 : 3

At first, the pointer was pointed to the 0th position. Then we have changed it to the 3rd position using seek().

Conclusion :

We have checked different examples of RandomAccessFile in this post. Always remember to open the file in the correct mode, i.e. if you are opening it only for reading, open it in ‘r’ mode, not in ‘rw’ mode. Also, always close it using close() method after completing your job. RandomAccessFile contains a few more methods. You can check the official guide here for more info on it.

Leave a Reply