RandomAccessFile is a java.io.File interface class that can be used to store binary data in a file, and get it back from the file as a byte array. The class is useful when you need to access the data in a random way, like when the file is too big to store in memory.
The RandomAccessFile class in Java (JSR-107) is a non-blocking, generic, write-only file object class that provides a simple, lightweight, generic and thread-safe method to read and write files. This is a very helpful class for concurrent programming, but the implementation is not straightforward, and the API is slightly confusing to use.
RandomAccessFile in Java is a class that allows you to read data from a file and write it anywhere in the file. In other words, the RandomAccessFile class can be used to create files that can be used to read and write data with random access. Random access means that the stored data is accessed in the order desired by the user. That is, we can refer to the data in the file in any order in which we use the file. Such a file is called a random access file. A random access file is a file that can be used for both reading and writing using the RandomAccessFile class in Java.
Why do I need the class RandomAccessFile in Java?
So far, we have looked at all I/O streams that can be used for read-only or write-only operations, but not for both at the same time. In other words, all the I/O streams we have used so far are known as read-only or write-only streams. Such threads are called sequential threads in Java. A file that is read or written using a sequential flow is called a sequentially opened file. The data in the sequential access file cannot be updated. Therefore, Java provides the class RandomAccessFile to read and write data simultaneously. A file class with random access allows us to change the location in the file where the next read or write will occur. The class RandomAccessFile was added in Java version 1.0. It is available in the java.io.RandonAccessFile package.
Statement about the Java class RandomAccessFile
The class RandomAccessFile is an extension of the class Object and implements the interfaces DataInput and DataOutput with additional methods to support random access. So it can be used to read and write at the same time. It also implements the Closeable and AutoCloseable interfaces. It is not inherited from the InputStream or OutputStream superclass. The general syntax for declaring the class RandomAccessFile in Java is as follows: public class RandomAccessFile extends Object implements DataOutput, DataInput, Lockable, AutoCloseable
File pointer to the class RandomAccessFile
A random access file consists of a sequence of bytes. It supports a special pointer called a file pointer. The file pointer indicates the current position (location) in the file. It is located in one of the bytes of the file and can be moved to any position in the file before reading or writing. In other words, the read or write operation takes place at the location of the file pointer. The file pointer can be moved using the seek() method of the RandomAccessFile class. When a file is created for the first time, the file pointer is given the value 0, indicating the beginning of the file. When we read or write data to a file using the read or write methods, the file pointer advances to the next data element (i.e., the next byte). If we are. B. read an int value from a file with the readInt() method, the JVM reads 4 bytes with the file pointer, and now the file pointer is 4 bytes ahead of the previous position, as shown in the figure below In the RandomAccessFile raf method, raf.seek(position) moves the file pointer to the specified location. raf.seek(0) moves the file pointer to the beginning of the file, and raf.seek(raf.length()) – to the end of the file.
Constructors of the class RandomAccessFile
The RandomAccessFile class defines the following constructors in Java. They are as follows: 1. RandomAccessFile(FileObj, String mode) : This constructor creates a random-access file stream with the specified file object and mode. Here fileObj defines the name of the file to be opened as a file object. 2. RandomAccessFile(String filename, String mode) : This constructor creates an arbitrary access file stream with a specified file name and mode. In both cases, the mode determines what type of file access is allowed. For example:
- If the mode is (as a rule) r, the file can only be read, but not written.
- If it is equal to rw, the file is opened in read-write mode.
- If it is rws, the file is opened in read-write mode, and all changes to the file data are immediately written to the physical device.
The general syntax for creating a new file stream for read and write operations is given below: RandomAccessFile raf = new RandomAccessFile(myfile.dat, rw) ; Here rw is the mode string passed as a parameter to the constructor of the RandomAccessFile class. When a file is opened using the above syntax, the file pointer is automatically placed at the beginning of the file. Using the above syntax, the program can read and write to the file myfile.dat. If myfile.dat already exists, raf is created to access it; if myfile.dat does not exist, a new file named myfile.dat is created, and raf is created to access the new file.
RandomAccessFile methods in Java
Java’s class RandomAccessFile defines some important additional methods to support random access. They are as follows:
Methods | Description |
1. void close() : | This method closes the arbitrary file stream and releases all system resources associated with the stream. |
2. FileChannel getChannel() : | This method returns a unique FileChannel object associated with the file. |
3. FileDescriptor getFD() : | This method returns an opaque file descriptor object associated with the underlying thread. |
4. long getFilePointer() : | This method gives the current offset (in bytes) between the beginning of the file and the next read or write position. |
5. long length() : | This method gives the length (number of bytes) of the specified file. |
6. int read() : | It reads one byte of data from this file and returns -1 at the end of the stream. |
7. int read(byte[ ] b) : | It reads up to b.length bytes of data from this file into a byte array. |
8. int read(byte[ ] b, int n, int m) : | It reads up to m bytes of data from this file into a byte array, starting with the nth byte. |
9. boolean readBoolean() : | This method reads a boolean value from the specified file. |
10. readByte() : | This method reads an eight-bit signed value from the specified file. |
char readChar() : | This method reads a character value from the specified file. |
12. double readDouble() : | The readDouble() method reads a double value from this file. |
13. float readFloat() : | The readFloat() method reads a float value from this file. |
14. void readFully(byte[ ] b) : | It reads the bytes of length b.length from this file into a byte array, starting with the current file pointer. |
15. void readFully(byte[ ] b, int n, int m) : | It reads exactly m bytes from this file into a byte array, starting with the current file pointer. |
16. String readLine() : | The method readLine() reads the following text line from this file. |
17. String readUTF() : | The readUTF() method reads a string from this file. |
void seek(long pos) : | This method sets a file pointer (in bytes, specified in pos) measured from the beginning of this file where the next read or write will occur. |
void setLength(long newLength) : | The function setLength() sets the new length for this file. |
20. int skipBytes(int n) : | This method skips n bytes of the input data and discards the skipped bytes. |
21. void write(byte[ ] b) : | This method writes the b.length bytes of the specified byte array to the specified file, starting with the current file pointer. |
22. void write(byte[ ] b, int n, int m) : | This method writes m bytes of the specified byte array, starting with the nth byte, to the specified file. |
23. void write(int b) : | The write() method writes the specified byte to this file. |
24. void writeBoolean(boolean v) : | It writes a boolean value (one byte) to the file. |
25. void writeByte(int v) : | It writes a value (a byte) to the file. |
26. void writeBytes(String s) : | It writes a string value as a series of bytes to a file. |
void writeChar(int v) : | It writes a character to the file as a two-byte value, high byte first. |
28. void writeChars(String s) : | It writes a string to the file as a sequence of characters. |
void writeDouble(double v) : | First, the specified double value is converted to a long value using the doubleToLongBits method of the Double class, and then that long value is written to the file as a set of eight bytes, the highest byte first. |
30. void writeFloat(float v) : | It first converts the specified float value to an int value using the floatToIntBits method of the Float class, and then writes that int value to the file as a set of four bytes, highest byte first. |
31. void writeInt(int v) : | It writes an int value as four bytes to the file, with the most significant byte being the first. |
void writeLong(long v) : | It writes a long value in the form of eight bytes to the file, the highest byte first. |
33. void writeShort(int v) : | It writes a short value as two bytes to the file, the high byte first. |
34. void writeUTF(String str) : | It writes a string value in a modified UTF-8 encoding to a file in a machine-independent manner. |
RandomAccessFile Example programs
Let’s look at an example program based on the above methods defined by the RandomAccessFile class in Java. Program source code 1 : package javaProgram; import java.io.IOException; import java.io.RandomAccessFile; public class RandomIO { public static void main(String[] args) throws IOException { // Create the Random Access File object. RandomAccessFile file = new RandomAccessFile(myfile.dat, rw) ; // Write to the file. file.writeChar(‘S’); file.writeInt(2222); file.writeDouble(222,22) ; file.seek(0); // Move the file pointer to the beginning. // Read data from a file. System.out.println(file.readChar()); System.out.println(file.readInt()); System.out.println(file.readDouble()) ; file.seek(2); // Move the file pointer to the second element. System.out.println(file.readInt()) ; // Go to the end and add a boolean value in the file. file.search(file.length()); file.writeBoolean(true) ; // Because the pointer is at the end, outside the 4. the file pointer is moved to the 4th element. in the file is moved. file.seek(4); // Moves the file pointer to the 4th element in the file. Element. System.out.println(file.readBoolean()); // 4. Reads the element. file.close(); // Closes the stream. } } Exit: S 2222 222,22 2222 where Explanation: This program opens a file with random access and then performs read and write operations. (a) Write three pieces of data to a file using the writeChar(), writeInt(), and writeDouble() methods. b) Move the file pointer to the beginning of the file using the seek() method. c) Read the three elements of the file and print them on the console. d) Now take the pointer from the file to the second element (2222), then read the second element of the file and print it. e) Moves the pointer to the end with the length() method and then inserts the second element into the file. f) Since there are now four elements in the file and the pointer is at the end, outside the fourth element, it takes the file pointer to the fourth element and executes it. (g) Close the file at the end using the close() method. The output is displayed on the console. Let’s create a program to add an item to an existing file using the class RandomAccessFile. Take a look at the following source code. Program source code 2 : package javaProgram; import java.io.IOException; import java.io.RandomAccessFile; public class RandomIO { public static void main(String[] args) throws IOException { // Create the Random Access File object. RandomAccessFile file = new RandomAccessFile(D:\cityfile.txt, rw) ; file.seek(file.length()); // Move the file pointer to the end. file.writeBytes(nDhanbad); // Add Dhanbad. file.close(); System.out.println(Successfully written…); } } Exit: Successfully written… the content of the file cityfile.txt before execution: Sydney New York Mumbai the content of the file cityfile.txt after execution: Sydney New York Mumbai Dhanbad 3. For practical purposes, let’s look at another example of a program based on the file access methods described above. Program source code 3 : package javaProgram; import java.io.IOException; import java.io.RandomAccessFile; public class RandomIO { public static void main(String[] args) throws IOException { // Create the Random Access File object. RandomAccessFile file = new RandomAccessFile(iofile.dat, rw) ; // Clean up the file to destroy old data if it exists. file.setLength(0); // Empty file. // Write new integers to the file. for(int i = 0; i <= 10; i++) { file.writeInt(i); } // Display the current length of the file. System.out.println(Current file length: +file.length()) ; // Retrieve the first number of the file. // Move the file pointer to the beginning. file.seek(0); System.out.println(First number: +file.readInt()) ; // Get the second file number. System.out.println(Second number: +file.readInt()) ; //The number in the 9. Position obtained. // File pointer to 9. Move the position. file.seek(9 * 4); System.out.println(number nine: +file.readInt()) ; // Change the number of tenths. file.writeInt(222); file.seek(10 * 4); // Set the pointer to position 10. System.out.println(Tenth number : +file.readInt()) ; // Add a new number to the end of the file. file.seek(file.length()); file.writeInt(333); // Output the new file length. System.out.println(New file length: +file.length()) ; // Get a new number. Moves the file pointer to the new number.file.seek(11 * 4);System.out.println(New number: +file.readInt());} Exit: Current file length : 44 Number 1 : 0 Second number: 1 , item 9 : 9 Number 10 : 222 Length of new file : 48 New number : 333 Explanation: a) RandomAccessFile creates a file named infile.dat with rw mode to allow read and write operations. b) file.setLength(0) sets the length to 0 to delete the file. It destroys the old data in the file. c) The for loop writes 11 int values from 0 to 10 to the file. Since each int value takes up 4 bytes, the total file length returned by file.length() is now 44, as shown in the output. d) Calling file.seek(0) puts the file pointer at the beginning of the file. file.readInt() reads the first value and moves the file pointer to the next number. The second digit shall be read as 1. e) file.seek(9 * 4) moves the file pointer to the ninth number. file.readInt() reads the ninth number and moves the file pointer to the tenth number. (f) file.write(222) writes the new tenth number to the current position. The previous tenth issue was completely destroyed. g) file.seek(file.length()) moves the file pointer to the end of the file. h) file.writeInt(333) writes the number 333 to the file. The file length will now be increased by 4. Therefore, file.length() returns 48. i) file.seek(11 * 4) moves the file pointer to the eleventh digit. The new eleventh issue, 333, appears as in the above issue. I hope this tutorial has covered all the important points about the RandomAccessFile class in Java with example programs. I hope you understand the basics of the random access file class. Thanks for reading!!!
Frequently Asked Questions
What is RandomAccessFile in Java?
RandomAccessFile is a java class to handle file reading and writing. This is the RandomAccessFile API. The RandomAccessFile class is a useful utility class that can be used to create a simple file system that allows files to be read in random order, instead of in the order in which they were created.
How do you write a RandomAccessFile in Java?
RandomAccessFile is a Java library which can create and read files with random access. The RandomAccessFile class has many methods to read and write data to the file. It has methods to read and write bytes, characters, strings, lines, and pages. It can also read entire files. In this blog post, we are going to learn how to write a random access file (also called a file stream/file view or file buffer) in Java.
How does RandomAccessFile work in Java?
All of us have encountered RandomAccessFile at some point or the other. We use these classes in our daily work, but few of us are aware of how they actually work. Today we will be explaining how RandomAccessFile works in Java and how to use them. An alternative way to do random reading in Java is using a RandomAccessFile. (If you have a chance, check out the original article on this topic.) RandomAccessFile is a primitive type that can be used to read a sequence of bytes from a file. Unlike a traditional byte array, the bytes in a RandomAccessFile are guaranteed to be non-NULL. This can be useful in situations where you want to read the same amount of data from a file, but want to do it in a random order. (It’s also useful for reading data out of a binary file that’s not necessarily in byte order.)
Related Tags:
randomaccessfile java 8random access file in java geeksforgeeksjava randomaccessfile performancerandom access file in java pptrandomaccessfile java 11java randomaccessfile seek,People also search for,Feedback,Privacy settings,How Search works,randomaccessfile java 8,random access file in java geeksforgeeks,java randomaccessfile performance,random access file in java ppt,randomaccessfile java 11,java randomaccessfile seek,random access class in java,randomaccessfile android