How to read a .txt file with RandomAccessFile in Java?


In general, while reading or writing data to a file, you can only read or, write data from the start of the file. you cannot read/write from random position.

The java.io.RandomAccessFile class in Java enables you to read/write data to a random access file.

This acts similar to a large array of bytes with an index or, cursor known as file pointer you can get the position of this pointer using the getFilePointer() method and set it using the seek() method.

This class provides various methods to read and write data to a file. The readLine() method of this class reads the next line from the file and returns it in the form as String.

To read data from a file using the readLine() method of this class −

  • Instantiate the File class by passing the path of the required file in String format.

  • Instantiate the StringBuffer class.

  • Instantiate the RandomAccessFile class by passing the above created File object and a String representing mode of access (r:read, rw:read/write etc..)

  • iterate through the file while its position is less than its length (length() method).

  • Append each line to the StringBuffer object created above.

Example

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
   public static void main(String args[]) throws IOException {
      String filePath = "D://input.txt";
      //Instantiating the File class
      File file = new File(filePath);
      //Instantiating the StringBuffer
      StringBuffer buffer = new StringBuffer();
      //instantiating the RandomAccessFile
      RandomAccessFile raFile = new RandomAccessFile(file, "rw");
      //Reading each line using the readLine() method
      while(raFile.getFilePointer() < raFile.length()) {
         buffer.append(raFile.readLine()+System.lineSeparator());
      }
      String contents = buffer.toString();
      System.out.println("Contents of the file: \n"+contents);
   }
}

Output

Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to encourage 
our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content

Updated on: 14-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements