Explanation
This Java program demonstrates how to read from and write to a file at arbitrary positions using the RandomAccessFile class. Unlike standard sequential stream classes (such as FileInputStream and FileOutputStream), which require you to read data from the beginning to the end, RandomAccessFile allows you to jump directly to any specific byte position within a file.
Here is a step-by-step breakdown of how the code works:
-
File Initialization: The program instantiates a
RandomAccessFileobject namedfiletargeting a local file named"sample.txt". It uses the"rw"(read-write) mode, which allows both reading from and writing to the file. If"sample.txt"does not exist, Java automatically creates it. -
Writing Binary Data: The program writes three primitive values sequentially:
file.writeInt(101);— Writes an integer (takes up 4 bytes).file.writeDouble(99.99);— Writes a double-precision floating-point number (takes up 8 bytes).file.writeChar('A');— Writes a character (takes up 2 bytes in UTF-16 representation).
At this point, the file contains a total of 14 bytes of binary data, and the internal file pointer is positioned at the very end of the file (byte index 14).
-
Resetting the File Pointer: To read the data back from the beginning, the program calls
file.seek(0). This moves the file pointer back to index0(the first byte of the file). -
Sequential Reading: The program reads the data back in the exact order it was written using
readInt(),readDouble(), andreadChar(). It is critical to read the data in the correct sequence because the file is stored in a raw binary format; reading a double where an integer is stored would result in corrupted or meaningless data. The values are then printed to the console. -
Demonstrating Random Access: This is the core feature of the class. The program calls
file.seek(4). Because the integer written at the start occupies exactly 4 bytes (indices 0 to 3), the byte index 4 is the exact starting position of the double value (99.99). By seeking directly to index 4, the program bypasses the integer entirely and reads the double value directly usingfile.readDouble(). -
Resource Cleanup and Exception Handling: The file is closed using
file.close()to release operating system resources. The entire block is wrapped in atry-catchblock to handle any potentialIOExceptionthat might arise (e.g., file permission issues or disk errors).