Last Updated:

RandomAccessFile in Java  | Example

Today we will look at how to use RandomAccessFile, as well as why it is needed and how to use it.

RandomAccessFile. Theory

RandomAccessFile Java provides the ability to read from a file and write data to a file. works with the file as a large byte array. It uses a cursor with which we can move the file pointer to a specific position.RandomAccessFile

When creating an instance, we have to choose a file mode, for example if you want to read data from a file or – if you want to read from a file and write to a file.RandomAccessFile"r""rw"

With the help of the file pointer, we can read from the file or write data to the file anywhere. To get the current file pointer, use the .getFilePointer()

To set the index of the file pointer, use the .seek(int i)

It should be noted that if we write to the file by index, where the data is already present, then they will be replaced.

RandomAccessFile in Java. Example of use

 

Stay tuned for updates in the Java IO section.