Updating a file rondom access

Open file in rw mode to write to file using Random Access File.

You can write anywhere in the file by setting pointer to the position where you want to write using seek() method.

Java IO character streams and byte streams access files sequentially.

Java IO provides Random Access File class which allows you to access files randomly.

Random Access File provides methods to read and write to files.

To read byte by byte, you can read() method and to read file content into bytes array, you need to pass byte array to read() method.

You can randomly read file using File Channel by setting the position to a desired location and reading content from that location or specific number of bytes.

You can set the length of contents of a file using set Length() method.

In order for the method to work, first two bytes after the current pointer should tell how many number of bytes after the two bytes should be used for decoding and returning as string.

If a string is not written using write UTF(), there is a high probability that using read UTF() to read the string will throw end of file exception (EOFEexception).

You need to open the file for write access in order to use set Length() method, otherwise, you will get access denied IO exception.

You can use read UTF() method to read a string encoded in UTF-8 format.

Leave a Reply