
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read TXT File with RandomAccessFile in Java
In general, while reading or writing data to a file, you can do so, 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 where the cursor known as file pointer works like an index. With the help of file pointer you can get the position of this pointer using the getFilePointer() method and set it using the seek() method.
RandomAccessFile Class: Reading Files
This class provides various methods to read and write data to a file -
Using readLine()
Using read()
Using seek()
Using getFilePointer(): It returns the current file pointer location in the file.
length(): It returns the total length of the file in bytes.
Using readLine() method
The readLine() method of the RandomAccessFile reads one line at a time. It does not include the line break at the end, so you will need to add them manually using System.lineSeparator().
In this program, we use RandomAccessFile to open the file and read it line by line using the readLine() method. Each line is added to a buffer until the end of the file is reached, and then we print the full content.
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileExample { public static void main(String[] args) throws IOException { // Use a relative path (file should be in the same folder as the code) String filePath = "D:/input.txt"; // Create a File object for the input file File file = new File(filePath); // Create a StringBuffer to store the content of the file StringBuffer buffer = new StringBuffer(); // Open the file in read/write mode RandomAccessFile raFile = new RandomAccessFile(file, "rw"); // Read each line and add it to the buffer while (raFile.getFilePointer() < raFile.length()) { // Note: readLine() doesn't include the line break, so we add it manually buffer.append(raFile.readLine()).append(System.lineSeparator()); } // Convert the buffer to a string and print it String contents = buffer.toString(); System.out.println("Contents of the file:\n" + contents); // Close the file raFile.close(); } }
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
Using seek() method with ReadLine()
The seek() method moves the file pointer to a specific position. If we need to read/write from a specific position of a file we can use this method with the readLine() method.
In this program, we are reading a file starting from a specific position instead of the beginning. Using the seek(100) method, we move the file pointer to byte 100 and read everything from there till the end.
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFromPosition { public static void main(String[] args) throws IOException { // File path (make sure this file exists on your system) String filePath = "D:/input.txt"; // Create a File object and open the file in read/write mode File file = new File(filePath); RandomAccessFile raFile = new RandomAccessFile(file, "rw"); // Move the file pointer to byte position 100 raFile.seek(100); // Read the rest of the file from that position StringBuffer buffer = new StringBuffer(); while (raFile.getFilePointer() < raFile.length()) { buffer.append(raFile.readLine()).append(System.lineSeparator()); } // Print the contents read from position 100 String contents = buffer.toString(); System.out.println("Contents from position 100:\n" + contents); // Close the file raFile.close(); } }
Output
refer 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
Using the read() method and a Loop
The read() method reads one character/byte at a time and can be used to read specific character ranges. To read the contents of an entire file we need to use this method within a loop.
Example
In this program, we are reading the first 100 characters of a .txt file using the read() method. We are using a for loop to read each character one by one from the file and make a string.
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class ReadFirstNCharacters { public static void main(String[] args) throws IOException { String filePath = "D:/input.txt"; // Create a File object and open it using RandomAccessFile in read mode File file = new File(filePath); RandomAccessFile raFile = new RandomAccessFile(file, "r"); // Read first 100 characters one by one int n = 100; StringBuilder result = new StringBuilder(); for (int i = 0; i < n && raFile.getFilePointer() < raFile.length(); i++) { result.append((char) raFile.read()); } System.out.println("First 100 characters of the file:\n" + result); // Close the file raFile.close(); } }
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.
Using readLine() in a Loop
In this Java program, we read the file line by line and keep track of the line number. When we reach the line we want, we print it.
We use a while loop with readLine() to read the file line by line. By keeping a counter for the current line number, we check when it matches the line we want and print it out.
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class ReadSpecificLine { public static void main(String[] args) throws IOException { String filePath = "D://input.txt"; // Create File and RandomAccessFile objects File file = new File(filePath); RandomAccessFile raFile = new RandomAccessFile(file, "r"); int targetLine = 3; // Line number to read (e.g., line 3) int currentLine = 1; String line; while ((line = raFile.readLine()) != null) { if (currentLine == targetLine) { System.out.println("Line " + targetLine + ": " + line); break; } currentLine++; } // Close the file raFile.close(); } }
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.
Using seek() and read() method
In this program, we are reading a file from the end toward the beginning using a loop. We use seek() method to move the pointer backward and read() to get one character at a time, building the reversed content step by step.
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class ReadFileInReverse { public static void main(String[] args) throws IOException { String filePath = "D://input.txt"; // Create a File object and open it with RandomAccessFile File file = new File(filePath); RandomAccessFile raFile = new RandomAccessFile(file, "r"); // Start reading from the last character long fileLength = raFile.length(); StringBuilder reversedContent = new StringBuilder(); for (long pointer = fileLength - 1; pointer >= 0; pointer--) { raFile.seek(pointer); char ch = (char) raFile.read(); reversedContent.append(ch); } // Print reversed content System.out.println("File content in reverse:"); System.out.println(reversedContent.toString()); // Close the file raFile.close(); } }
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