In this section, you will learn the use of RandomAccessFile class.
RandomAccessFile allows read and write operations to any specified location in a file. Here data can be read from or written to in a random manner. Unlike other input and output streams, RandomAccessFile is used for both reading and writing files. A random access file treats with a large array of bytes and uses the file pointer to deal with the index of that array. This file pointer points the positions in the file where the reading or writing operation has to be done. It defines operation modes (read / write).
r mode- Open for reading only.
rw mode- Open for reading and writing.
seek(file.length()) method- It jumps the file pointer at the specified location. Here, file.length( ) returns the end of the file.
rand.close() method- It closes the random access file stream.
writeBytes( ) method- It simply writes the content into the file.
readByte() method- It reads a single byte from the file.
readLine() method- It reads the line from the file.
If you want to perform read operation with RandomAccessFile, then you have to create an instance with 'r' mode:
RandomAccessFile access = new RandomAccessFile(file, "r");
and if you want to perform write operation with RandomAccessFile, then you have to create an instance with 'rw' mode:
RandomAccessFile access = new RandomAccessFile(file, "rw");
Here we have created two examples performing read and write operations respectively.
Example performs read operation:
Example performs write operation:
Recommend the tutorial