O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required