Java Reference
In-Depth Information
Random Access to a File
We can already read or write 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 we
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 we 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 we can access a file randomly using the read() method above.
Try It Out - Reading a File Randomly
To show how easy it is to read from random positions in a file, we will write an example to extract a
random selection of values from our primes.bin file. Here's the code:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class RandomFileRead {
public static void main(String[] args) {
File aFile = new File("C:/Beg Java Stuff/primes.bin");
FileInputStream inFile = null;
FileOutputStream outFile = null;
try {
inFile = new FileInputStream(aFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inFile.getChannel();
Search WWH ::




Custom Search