writing-and-reading-data-in-file-using-RandomAccessFile-in-java-with-examples

admin

2/27/2025

Java.io.RandomAccessFile Class Method

Go Back

Java.io.RandomAccessFile Class Method Import RandomAccessFile in Java with Examples

Updated: 06/Feb/2025 by Computer Hope

Introduction

In Java, the RandomAccessFile class allows reading and writing data to a file at any position. This feature makes it ideal for applications that require efficient file manipulation. Unlike FileWriter and FileReader, RandomAccessFile provides both read and write capabilities and enables seeking a specific position within a file.

In this tutorial, we will explore how to use RandomAccessFile to write and read data in a file using Java, along with practical examples.


Java.io.RandomAccessFile Class Method

Understanding RandomAccessFile in Java

The RandomAccessFile class in Java's java.io package provides methods such as:

  • writeInt(int value) – Writes an integer to the file.
  • writeDouble(double value) – Writes a double value to the file.
  • writeBoolean(boolean value) – Writes a boolean value to the file.
  • readInt() – Reads an integer from the file.
  • readDouble() – Reads a double value from the file.
  • readBoolean() – Reads a boolean value from the file.
  • seek(long position) – Moves the file pointer to a specified position.

Example 1: Writing and Reading Data Using RandomAccessFile

This example demonstrates writing an integer, double, and boolean value to a file using writeInt(), writeDouble(), and writeBoolean(). It then reads and prints the data using readInt(), readDouble(), and readBoolean().

import java.io.*;

class FileExample7 {
    public static void main(String args[]) {
        try {
            RandomAccessFile rac = new RandomAccessFile("d:/assignments/mydata.dat", "rw");
            
            // Writing data to file
            rac.writeInt(1024);
            rac.writeDouble(456.45);
            rac.writeBoolean(true);
            
            System.out.println("File size is " + rac.length() + " bytes");
            
            // Reading data from file
            rac.seek(0);
            int intValue = rac.readInt();
            double doubleValue = rac.readDouble();
            boolean booleanValue = rac.readBoolean();
            
            System.out.println("Integer value: " + intValue);
            System.out.println("Double value: " + doubleValue);
            System.out.println("Boolean value: " + booleanValue);
            
            rac.close();
        } catch (Exception ex) {
            System.out.println("Error in writing or reading Object");
        }
    }
}

Example 2: Storing and Retrieving Prime Numbers

This example demonstrates how to write prime numbers to a file and retrieve a specific prime number based on user input.

import java.io.*;
import java.util.*;

class FileExample8 {
    public static void main(String args[]) {
        try {
            RandomAccessFile rac = new RandomAccessFile("d:/assignments/primenos.dat", "rw");
            Scanner kb = new Scanner(System.in);
            
            System.out.println("Enter a number:");
            int n = kb.nextInt();
            
            // Writing prime numbers to file
            first:
            for (int i = 2; i <= n; i++) {
                for (int j = 2; j <= i - 1; j++) {
                    if (i % j == 0) continue first;
                }
                rac.writeInt(i);
            }
            
            System.out.println("Enter a position:");
            int pos = kb.nextInt();
            int count = (int) (rac.length() / 4);
            
            if (pos > count) {
                System.out.println("Invalid position");
            } else {
                rac.seek((pos - 1) * 4);
                int primeNo = rac.readInt();
                System.out.println("Prime number at position " + pos + " is " + primeNo);
            }
            
            rac.close();
        } catch (Exception ex) {
            System.out.println("Error in writing or reading Object");
        }
    }
}

Key Takeaways

  • RandomAccessFile allows both reading and writing operations at any position within a file.
  • Methods such as seek() enable random access, making it more efficient than sequential file readers and writers.
  • writeInt(), writeDouble(), and writeBoolean() store different types of data.
  • readInt(), readDouble(), and readBoolean() allow retrieving the stored data.
  • Useful for applications requiring quick access to specific file data, such as databases, index-based file processing, and caching systems.

Conclusion

The RandomAccessFile class in Java is a powerful tool for handling files efficiently. It enables both sequential and random file access, making it a preferred choice for working with structured file storage and retrieval. By using seek(), you can quickly navigate through large files, enhancing performance compared to traditional file handling techniques.


Would you like me to add more details or modify any section for better clarity? 🚀

Table of content