11.7. Random Access to a File

You can already read from or write to a file at random. The FileChannel class defines both a read() and a write() method that operate at a specified position in the file:

read(ByteBuffer buf,
     long position)
Reads bytes from the file into buf in the same way as you have seen previously except that bytes are read starting at the file position specified by the second argument. The channel's position is not altered by this operation. If position is greater than the number of bytes in the file, then no bytes are read.
write(ByteBuffer buf,
    long position)
Writes bytes from buf to the file in the same way as you have seen previously except that bytes are written starting at the file position specified by the second argument. The channel's position is not altered by this operation. If position is less than the number of bytes in the file, then bytes from that point will be overwritten. If position is greater than the number of bytes in the file then the file size will be increased to this point before bytes are written. In this case the bytes between the original end-of-file and where the new bytes are written will contain junk values.

These methods can throw the same exceptions as the corresponding method accepting a single argument; plus, they may throw an exception of type IllegalArgumentException if a negative file position is specified.

Let's see how you can access a file randomly using the preceding read() method.

Try It Out: Reading a File Randomly ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.