Java Reference
In-Depth Information
Let's try the first approach first because it's easier.
To read the string length you need a byte buffer with a capacity to hold a single value of type double :
ByteBuffer lengthBuf = ByteBuffer.allocate(8);
You can create byte buffers to hold the string and the binary prime value, but you can only create the
former after you know the length of the string. Remember, you wrote the string as Unicode characters so
you must allow 2 bytes for each character in the original string. Here's how you can define the buffers for
the string and the prime value:
ByteBuffer[] buffers = {
null, // Byte buffer to hold string
ByteBuffer.allocate(8) // Byte buffer to hold prime
};
The first element in the array is the buffer for the string. This is null because you redefine this as you
read each record.
You need two read operations to get at all the data for a single prime record. A good approach would be
to put both read operations in an indefinite loop and use a break statement to exit the loop when you hit the
end-of-file. Here's how you can read the file using this approach:
while(true) {
if(inCh.read(lengthBuf) == -1) // Read the string length,
break; // if its EOF exit the loop
lengthBuf.flip();
// Extract the length and convert to int
strLength = (int)lengthBuf.getDouble();
// Now create the buffer for the string
buffers[0] = ByteBuffer.allocate(2*strLength);
if(inCh.read(buffers) == -1) { // Read the string & binary prime value
// Should not get here!
System.err.println("EOF found reading the prime string.");
break; // Exit loop on EOF
}
// Output the prime data and clear the buffers for the next iteration...
}
After reading the string length into lengthBuf you can create the second buffer, buffers[0] . The
getDouble() method for lengthBuf provides you with the length of the string. You get the string and the
binary prime value the arguments to the output statement. Of course, if you manage to read a string length
value, there ought to be a string and a binary prime following, so you have output an error message to signal
something has gone seriously wrong if this turns out not to be the case.
Let's see how it works out in practice.
Search WWH ::




Custom Search