Java Reference
In-Depth Information
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel file = outputFile.getChannel();
The file extension has been changed to .txt to differentiate it from the original binary file that we
wrote. We will want to make use of both the binary file and this file when we are looking into file read
operations.
The byte buffer has to be large enough to hold the double value that counts the characters in the
string, the string itself, plus the long value for the prime. The original byte buffer with 100 bytes
capacity will be plenty big enough so let's go with that:
final int BUFFERSIZE = 100; // Buffer size in bytes
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
We need to create three view buffers from the byte buffer, one that will hold the double value for the
count, one for the string, and one for the binary prime value, but there is a problem.
buf
longBuf
doubleBuf
charBuf
The length of the string will depend on the number of decimal digits in the prime value, so we don't
know where it ends. This implies we can't map the last buffer to a fixed position. We are going to have
to set this buffer up dynamically inside the file-writing loop after we figure out how long the string for
the prime is. We can set up the first two view buffers outside the loop though:
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
buf.position(8);
CharBuffer charBuf = buf.asCharBuffer();
Search WWH ::




Custom Search