Java Reference
In-Depth Information
Now the file positions recorded by the channels are set explicitly and each channel's position is updated
when it executes an I/O operation. Note that the position() method for a channel does not return a
reference to the channel object so we cannot chain the position() and read() method calls
together. You can only do this with buffer objects.
One problem with the example as it stands is that some of the selections could be 99999L, which is
patently not prime. We could fix this by checking each value we store in the primes array:
for(int i = 0 ; i<PRIMESREQUIRED ; i++)
{
while(true)
{
index = 8*(int)(PRIMECOUNT*Math.random());
inChannel.position(index); // Set the file position
inChannel.read(buf); // and read from the file
buf.flip();
primes[i] = buf.getLong();
if(primes[i] != REPLACEMENT)
break;
else
buf.clear();
}
buf.flip();
buf.putLong(REPLACEMENT);
buf.flip();
outChannel.position(index); // Set the file position
outChannel.write(buf); // and write to the file
buf.clear();
}
The while loop now continues if the value read from the file is the same as REPLACEMENT , so another
random file position will be selected. This continues until something other than the value of
REPLACEMENT is found. Of course, if you run the example often enough, there won't be enough
primes in the file to fill the array so the program will loop indefinitely looking for something other than
REPLACEMENT . There are several ways you could deal with this. For instance, you could count how
many iterations have occurred in the while loop and bail out if it reaches the number of primes in the
file. You could also inspect the file first to see whether there are sufficient primes in the file to fill the
array. If there are exactly 10 you can fill the array immediately. I'll leave it to you to fill in these details.
Read/Write Operations with a Single File Channel
If you want to be able to read and write a file using a single channel, you must use the channel provided
by a RandomAccessFile object. A RandomAccessFile object is not related to the other file stream
classes since its only base class is Object . Its original purpose was to provide random access to a file,
which the other file stream classes could not, but as we have seen, this capability has been usurped by a
channel anyway.
Search WWH ::




Custom Search