Last Updated on March 20, 2023 by Prepbytes
Java provides various different tools and in-built classes for the developers to help them manipulate the files. One such class is RandomAccessFile Class. This class in Java allows the developer to read and write data at any position within the file. Any other file-handling classes in Java do not provide this facility. Let us learn about this RandomAccessFile in Java in detail, along with its methods and some practical use cases.
What is RandomAccessFile in Java?
The RandomAccessFile class in Java provides the ability to read and write data at any position within a file. It extends the java.io.File class and implements both the DataInput and DataOutput interfaces. This class provides random access to the contents of a file by using an offset pointer, which can be moved to any position within the file. This means that you can read or write data at any position within the file, not just from the beginning or end.
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 is a powerful and flexible class in Java that provides a lot of control when working with files. It allows you to read or write data at any position within the file, making it easier to manage large amounts of data. This class provides various methods for reading and writing data, With its ability to read and write data at any position within a file, it’s a valuable tool for managing large amounts of data and implementing complex file-based applications. While it may take some extra effort to use this class correctly, the benefits it provides make it well worth the investment.
Frequently Asked Questions (FAQs)
Here are some FAQs on RandomAccessFile in Java.
Ques 1. What happens if you try to read or write data outside the bounds of a RandomAccessFile in Java?
Ans. You’ll get an IOException with a message indicating that the operation is out of bounds.
Ques 2. Can you use RandomAccessFile with binary files in Java?
Ans. Yes, RandomAccessFile can be used to read and write binary data to a file.
Ques 3. Is RandomAccessFile thread-safe in Java?
Ans. No, RandomAccessFile is not thread-safe, so you’ll need to manage access to the file yourself if you’re working with multiple threads.
Ques 4. Can you read and write data to the same RandomAccessFile object simultaneously?
Ans. Yes, you can use the "rw" mode string when creating a RandomAccessFile object to allow for both reading and writing to the same file.