Using the RandomAccessFile class

This java code example illustrates how you can use the RandomAccessFile class.
The example in itself might seem pretty useless but the purpose is to show that you can both write to and read from a file with the same RandomAccessFile instance.
The RandomAccessFile class also enables you to get the current position of the file pointer by calling the method ‘getFilePointer’, or setting the file pointer position by calling the ‘seek’ method.

The behaviour of the RandomAccessFile class is similar to an array in the filesystem, but unlike an array you can alter the length of the file by calling the ‘setLength’ method.
If you are calling seek and then start to write data in an area that already contains data, it will be overwritten.

In this example we write two lines of code to the file, then we set the file pointer to the position at the end of the first line and read data from there and print it out.

The output to the file is:

and the output to the console:

Search for more Java info on this site here:
Custom Search

Please type any questions here.