handling-file-using-RandomAccessFile-class-in-java-with-examples

admin

2/27/2025

Read and Write Data in a File Using RandomAccessFile

Go Back

How to Read and Write Data in a File Using RandomAccessFile in Java (With Examples)

Introduction

Java provides multiple ways to handle file operations, and one of the most powerful classes for reading and writing files is RandomAccessFile. Unlike FileReader and FileWriter, RandomAccessFile allows us to read and write at any position within a file, making it useful for database-like applications and binary file handling.

In this tutorial, we'll explore how to use RandomAccessFile in Java, covering:

  • Writing data to a file using writeInt(), writeDouble(), writeLong(), and writeBoolean()
  • Reading data from a file using readBoolean(), readInt(), and readLong()
  • Using the seek() method to navigate within the file

What is RandomAccessFile in Java?

RandomAccessFile is a Java class that allows us to read and write data to files in a non-sequential order. This means we can move to any location in a file and modify or retrieve data as needed. It supports both read and write operations.

Key Features:

  • Allows both reading and writing operations.
  • Supports random access, meaning we can jump to a specific byte location.
  • Ideal for binary file manipulation.
  • Supports different data types such as int, double, long, and boolean.

Read and Write Data in a File Using RandomAccessFile

Writing and Reading Data Using RandomAccessFile in Java

Example 1: Writing and Reading Data from a File

The following example demonstrates how to use RandomAccessFile to write and read different types of data in Java.

Java Code Example:

import java.io.*;

class FileExample7 {
    public static void main(String args[]) {
        try {
            // Create a new file "mydata.dat" in read-write mode
            RandomAccessFile rac = new RandomAccessFile("D:/Assignments/mydata.dat", "rw");
            
            // Writing data to file
            rac.writeInt(1024);       // Writing an integer
            rac.writeDouble(456.45);   // Writing a double
            rac.writeLong(40000);      // Writing a long
            rac.writeBoolean(true);    // Writing a boolean
            
            System.out.println("File size is " + rac.length() + " bytes");
            
            // Moving pointer to the 4th byte to read double value
            rac.seek(4);
            double value = rac.readDouble();
            
            System.out.println("The double value is " + value);
            
            rac.close(); // Closing file
        } catch (Exception ex) {
            System.out.println("Error in writing or reading Object");
        }
    }
}

Explanation:

  1. File Creation: RandomAccessFile is opened in read-write ("rw") mode.
  2. Writing Data: Various data types (int, double, long, boolean) are written to the file.
  3. Reading Data: seek(4) moves the file pointer to a specific byte location to read the double value.
  4. Closing the File: Ensures the file is properly closed after operations.

Example 2: Updating a File Using seek()

The seek() method allows us to jump to a specific byte position and overwrite existing data. Let’s see an example where we update an existing file.

import java.io.*;

class UpdateFile {
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("D:/Assignments/mydata.dat", "rw");
            
            // Jump to the position of the long value (4 + 8 bytes)
            file.seek(12);
            
            // Update long value to 80000
            file.writeLong(80000);
            
            System.out.println("File updated successfully");
            file.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

How This Works:

  • We use seek(12) to move the pointer past the integer (4 bytes) and double (8 bytes).
  • The new long value 80000 is written, replacing the previous value 40000.

Advantages of RandomAccessFile Over Other File Handling Classes

Feature RandomAccessFile FileWriter/FileReader BufferedReader/BufferedWriter
Read & Write ✅ Supports both ❌ Separate classes needed ❌ Separate classes needed
Random Access ✅ Yes ❌ No ❌ No
Handles Binary Data ✅ Yes ❌ No ❌ No
Performance ⚡ High for large files ✅ Good for text ✅ Good for text

Conclusion

The RandomAccessFile class in Java provides a powerful way to read and write data at specific locations in a file. Unlike traditional FileReader and FileWriter classes, it allows random access, making it perfect for applications that require frequent updates to a file. By using methods like seek(), writeInt(), writeDouble(), and readLong(), you can efficiently manipulate file content in Java.

Key Takeaways:

  • RandomAccessFile is ideal for modifying large files.
  • Use seek() to navigate within the file.
  • Supports multiple data types like int, double, and boolean.

With this knowledge, you can now incorporate RandomAccessFile into your Java projects efficiently! 🚀

Table of content