Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

RandomAccessFile in Java

Last Updated on December 26, 2023 by Ankit Kochar

RandomAccessFile in Java is a powerful class that provides a convenient way to read from and write to a file with random access. Unlike other file I/O classes in Java, such as FileInputStream and FileOutputStream, RandomAccessFile allows you to move the file pointer to any position within the file and read or write data at that specific location. This flexibility makes RandomAccessFile particularly useful for scenarios where you need to perform random access operations on a file, such as updating specific portions of a file without reading and writing the entire file.
This class is part of the java.io package and provides methods to read and write different data types, including primitive types and strings. RandomAccessFile supports both reading and writing operations, allowing developers to create, modify, and navigate files efficiently.

What is RandomAccessFile in Java?

In Java, RandomAccessFile is a class in the java.io package that provides a mechanism for reading from and writing to a file randomly, as opposed to sequential access provided by other file I/O classes. This class allows you to move the file pointer to any position within the file and perform read or write operations at that specific location.

When you create a RandomAccessFile object, you can choose whether the file should be opened in read-only or read-write mode. The RandomAccessFile class supports two types of file access.

  • read-only: When you open a file in read-only mode, you can only read from it.
  • read-write: You can read and write data to a file if you open it in read-write mode.

Declaration of RandomAccessFile

The declaration of RandomAccessFile in Java is as given below.

public class RandomAccessFile
   extends Object
      implements DataOutput, DataInput, Closeable

Creating a RandomAccessFile Object in Java

To create a RandomAccessFile object, you need to pass the file path and the access mode as parameters to the constructor. Here’s an example:

RandomAccessFile file = new RandomAccessFile("data.txt", "rw");

Here, the file is being opened in the read-write mode.

Constructors of RandomAccessFile

In Java, the RandomAccessFile class has two constructors:

  • Constructor 1: RandomAccessFile(File fileObj, String mode)
    It generates a random access file stream to read, write, or execute the File Object specified.

  • Constructor 2: RandomAccessFile(String fileName, String mode)
    It generates a random access file stream to read, write, or execute the specified file name.

RandomAccessFile Class Methods

The RandomAccessFile class provides various methods for reading and writing data at any position within a file. Here are some of the most commonly used methods:

  • write()
    This method writes a byte of data to the file at the current file pointer position.

    Syntax of write():

    public void write(int b) throws IOException

    Example of write():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.write(65); //writes the ASCII code for 'A' to the file
  • writeBytes()
    The writeBytes() method writes a string of data to the file at the current file pointer position.

    Syntax of writeBytes():

    public void writeBytes(String s) throws IOException

    Example of writeBytes():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.writeBytes("Hello World");
  • writeChar()
    writeChar() writes a character to the file at the current file pointer position.

    Syntax of writeChar():

    public void writeChar(char c) throws IOException

    Example of writeChar():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.writeChar('A');
  • writeInt()
    This method is responsible for writing an integer to the file at the current file pointer position.

    Syntax of writeInt():

    public void writeInt(int i) throws IOException

    Example of writeInt():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.writeInt(42);
  • writeDouble()
    This method writes a double value to the file at the current file pointer position.

    Syntax of writeDouble():

    public void writeDouble(double d) throws IOException

    Example of of writeDouble():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.writeDouble(3.14);
  • seek()
    This method is used for setting the file pointer position to a specified location within the file.

    Syntax of seek():

    public void seek(long pos) throws IOException

    Example of seek():

    RandomAccessFile file = new RandomAccessFile("data.txt", "rw");
    file.seek(10); //sets the file pointer position to the 10th byte in the file
  • read()
    The method read() reads a byte of data from the file at the current file pointer position.

    Syntax of read():

    public int read() throws IOException

    Example of read():

    RandomAccessFile file = new RandomAccessFile("data.txt", "r");
    int data = file.read(); //reads a byte of data from the file
  • readBytes()
    This method reads a string of data from the file at the current file pointer position.

    Syntax of readBytes():

    public int read(byte[] b) throws IOException

    Example of readBytes():

    RandomAccessFile file = new RandomAccessFile("data.txt", "r");
    byte[] data = new byte[10];
    file.read(data); //reads 10 bytes of data from the file
  • readChar()
    readChar() method reads a character from the file at the current file pointer position.

    Syntax of of readChar():

    public char readChar() throws IOException

    Example of readChar():

    RandomAccessFile file = new RandomAccessFile("data.txt", "r");
    char data = file.readChar(); //reads a character from the file
  • readInt()
    It is responsible for reading an integer from the file at the current file pointer position.

    Syntax of readInt():

    public int readInt() throws IOException

    Example of readInt():

    RandomAccessFile file = new RandomAccessFile("data.txt", "r");
    int data = file.readInt(); //reads an integer from the file
  • readDouble()
    This method of RandomAccessFile method reads a double value from the file at the current file pointer position.

    Syntax of readDouble():

    public double readDouble() throws IOException

    Example of readDouble():

    RandomAccessFile file = new RandomAccessFile("data.txt", "r");
    double data = file.readDouble(); //reads a double value from the file

Example of RandomAccessFile in Java

Here is the code example, showing the usage of various methods taht are discussed above.

import java.io.*;


public class PrepBytes {
  public static void main(String[] args) {
    try {
      double d = 1.5;
      float f = 14.56f;


      // Creating a new RandomAccessFile - "dat"
      RandomAccessFile file = new RandomAccessFile("data", "rw");


      // Writing to file
      file.writeUTF("PrepBytes is an Ed-Tech Company");


      // File Pointer at index position - 0
      file.seek(0);


      // read() method :
      System.out.println("Use of read() method : " + file.read());


      file.seek(0);


      byte[] b = { 1, 2, 3 };


      // Use of .read(byte[] b) method :
      System.out.println("Use of .read(byte[] b) : " + file.read(b));


      // readBoolean() method :
      System.out.println("Use of readBoolean() : " + file.readBoolean());


      // readByte() method :
      System.out.println("Use of readByte() : " + file.readByte());


      file.writeChar('c');
      file.seek(0);


      // readChar() :
      System.out.println("Use of readChar() : " + file.readChar());


      file.seek(0);
      file.writeDouble(d);
      file.seek(0);


      // read double
      System.out.println("Use of readDouble() : " + file.readDouble());


      file.seek(0);
      file.writeFloat(f);
      file.seek(0);


      // readFloat() :
      System.out.println("Use of readFloat() : " + file.readFloat());


      file.close();


    } catch (IOException ex) {
      System.out.println("Something went Wrong");
      ex.printStackTrace();
    }
  }
}

Output:

Use of read() method : 0
Use of .read(byte[] b) : 3
Use of readBoolean() : true
Use of readByte() : 101
Use of readChar() : ▼
Use of readDouble() : 1.5
Use of readFloat() : 14.56

Explanation:
Here in the above example, we have first created a file named “data.txt” and then opened it in read-write mode. After that, we demonstrated the usage of read(), read(byte[] b), readBoolean(), readByte(), readChar(), readDouble(), and readFloat() methods. The output console shows the expected result.

Practical Use Cases

The RandomAccessFile class can be used in various practical applications where you need to read or write data at any position within a file. Here are some use cases where RandomAccessFile can be helpful:

  • Database management systems: RandomAccessFile can be used in database management systems to store and retrieve data from files. With RandomAccessFile, you can access data at any position within the file, which makes it easier to manage large amounts of data.
  • File compression: RandomAccessFile can also be used in file compression applications where data needs to be read or written at random positions within the file. This is because compression algorithms often require accessing data at random positions within the file.
  • Network protocols: RandomAccessFile can be used in network protocols where data needs to be read or written at specific positions within a file. For example, when sending and receiving files over a network, the data needs to be read and written at specific positions within the file.

Conclusion
In conclusion, RandomAccessFile in Java is a versatile tool for handling file I/O operations with random access requirements. Its ability to move the file pointer to any position in the file and perform read and write operations makes it a valuable asset for developers working on applications that involve manipulation of specific sections within a file. While it provides powerful features, developers should be cautious about using it in multithreaded environments, as RandomAccessFile is not inherently thread-safe.
Whether you are working on a database system, a file editor, or any application that requires efficient file manipulation, RandomAccessFile is a reliable choice for implementing random access operations in Java.

Frequently Asked Questions (FAQs) related to RandomAccessFile in Java

Here are some FAQs on RandomAccessFile in Java.

Q1: Is RandomAccessFile suitable for handling large files?
A1:
Yes, RandomAccessFile is well-suited for handling large files as it allows you to read and write data at specific positions without the need to load the entire file into memory. This makes it memory-efficient for working with files of considerable size.

Q2: Is RandomAccessFile thread-safe?
A2:
No, RandomAccessFile is not inherently thread-safe. If multiple threads need to access a RandomAccessFile concurrently, developers should use synchronization mechanisms to ensure proper coordination and avoid data corruption.

Q3: Can RandomAccessFile be used for both reading and writing operations?
A3:
Yes, RandomAccessFile supports both reading and writing operations. You can open a file in either "r" (read-only), "rw" (read and write), "rws" (read and write, and synchronize file content and metadata), or "rwd" (read and write, and synchronize file content) mode.

Q4: How do I move the file pointer to a specific position in the file?
A4:
You can use the seek(long pos) method to move the file pointer to the specified position in the file. The position is measured in bytes from the beginning of the file.

Q5: Are there any exceptions I need to handle when working with RandomAccessFile?
A5:
Yes, various IOExceptions, such as FileNotFoundException, IOException, and EOFException, can occur when working with RandomAccessFile. It’s essential to handle these exceptions appropriately to ensure the robustness of your file I/O operations.

Leave a Reply

Your email address will not be published. Required fields are marked *