Java Reference
In-Depth Information
These methods can throw the same exceptions as the corresponding method that accepts a single argu-
ment; plus, they might throw an exception of type
IllegalArgumentException
if a negative file position
is specified. Obviously, when you want to use a channel to read and write a file, you must specify both the
READ
and
WRITE
open options when you create the
FileChannel
object.
The
SeekableByteChannel
interface that the
FileChannel
class implements also declares an overload
of the
position()
method that accepts an argument of type
long
. Calling the method sets the file position
for the channel to the position specified by the argument. This version of the
position()
method returns
a reference to the channel object as type
FileChannel
. The interface also declares the
size()
method that
returns the number of bytes in the file to which the channel is connected. You could use this to decide on the
buffer size, possibly reading the whole file in one go if it's not too large.
Let's try an example that demonstrates how you can access a file randomly.
TRY IT OUT: Reading a File Randomly
To show how easy it is to read from random positions in a file, the example extracts a random selection
of values from our
primes.bin
file. Here's the code:
import java.nio.file.*;
import java.nio.channels.FileChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
public class RandomFileRead {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("primes.bin");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
program.");
System.exit(1);
}
final int PRIMESREQUIRED = 10;
final int LONG_BYTES = 8;
// Number of bytes for
type long
ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES*PRIMESREQUIRED);
long[] primes = new long[PRIMESREQUIRED];
int index = 0;
// Position for a prime
in the file
try (FileChannel inCh =
(FileChannel)(Files.newByteChannel(file))){
// Count of primes in the file
final int PRIMECOUNT = (int)inCh.size()/LONG_BYTES;