Java Reference
In-Depth Information
buffers[1] = ByteBuffer.wrap(primeStr.getBytes());
The wrap() method creates a buffer with a capacity that is the same as the length of the array with the
position set to zero and the limit to the capacity. Consequently, you don't need to flip the buffer — it is
already in a state to be written.
The third buffer in the array holds the binary prime value:
buffers[2].putLong(prime).flip();
This is essentially the same mechanism as you used to load the first buffer in the array. Here, you use
putLong() to store the prime value and call flip() using the reference that is returned.
The three buffers are ready, so you write the array of buffers to the file like this:
channel.write(buffers);
This applies the gathering-write operation to write the contents of the three buffers in the buffers array
to the file.
Finally, you ready the first and third buffers for the next iteration by calling the clear() method for each
of them:
buffers[0].clear();
buffers[2].clear();
Of course, the second buffer is re-created on each iteration, so there's no need to clear it. Surprisingly
easy, wasn't it?
FORCING DATA TO BE WRITTEN TO A DEVICE
A write() method for a channel returns when the write operation is complete, but this does not guarantee
that the data has actually been written to the file. Some of the data might still reside in the native I/O buffers
in memory. If the data you are writing is critical and you want to minimize the risk of losing it in the event
of a system crash, you can force completion of all outstanding output operations to a file that were previ-
ously executed by the channel by calling the force() method for the FileChannel object. The argument
to force() is a boolean value, false specifying that only the data needs to be forced to the storage device
and true specifying both data and metadata must be written. You could use it like this:
try( ... create the channel object... ) {
...
for(...) {
//Write to the channel...
outputChannel.force(true); // Force output to the file
// ...
}
} catch (IOException e) {
e.printStackTrace();
}
Search WWH ::




Custom Search