Java Reference
In-Depth Information
How It Works
All you had to do to write the file as well as read it was to create a
Path
object for the file and create a file
channel that is opened for both reading and writing. You can read and write sequentially or at random.
You read and write the file using essentially the same mechanism. You call the
position()
method for
the
channel
object to set the file position and then you call the
read()
or
write()
method with
buf
as
the argument.
You could have used the channel
read()
and
write()
methods that explicitly specify the position where
the data is to be read or written as an argument. In this case you would need to cast channel to type
FileChannel
. One problem with the example as it stands is that some of the selections could be
99999L
,
which is patently not prime. I got some of these after running the example just three times. You could fix
this by checking each value that you store in the
primes
array:
for(int i = 0 ; i < PRIMESREQUIRED ; ++i)
{
while(true)
{
index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
channel.position(index).read(buf);
// Read at a random
position
buf.flip();
// Flip the buffer
primes[i] = buf.getLong();
// Extract the prime
if(primes[i] != REPLACEMENT) {
break;
// It's good so exit the
inner loop
} else {
buf.clear();
// Clear ready to read
another
}
}
buf.flip();
// Flip to ready for
insertion
buf.putLong(REPLACEMENT);
// Replacement into buffer
buf.flip();
// Flip ready to write
channel.position(index).write(buf);
// Write the replacement
to file
buf.clear();
// Reset ready for next
read
}
RandomReadWrite.java
This code fragment is commented out in the download. The
while
loop now continues if the value read
from the file is the same as
REPLACEMENT
, so another random file position is selected. This continues
until something other than the value of
REPLACEMENT
is found. Of course, if you run the example often
enough, you won't have enough primes in the file to fill the array, so the program loops indefinitely look-
ing for something other than
REPLACEMENT
. You could deal with this in several ways. For example, you