Java Reference
In-Depth Information
strLength,
((ByteBuffer)(buffers[0].flip())).asCharBuffer().toString(),
((ByteBuffer)buffers[1].flip()).getLong());
You obtain the string by calling the asCharBuffer() method to obtain a CharBuffer object from the
original ByteBuffer and calling its toString() method to get the contents as a String object. It is
necessary to flip the byte buffer before you do this and you have to cast the reference returned by the
flip() method to type ByteBuffer in order to make this possible because flip( ) returns a reference of
type Buffer . You use a similar mechanism to get the binary prime value.
Finally you clear the buffers for the string length and prime value ready for the next loop iteration.
Compacting a Buffer
Another approach to reading the primes.txt file is to read bytes from the file into a large buffer for effi-
ciency and then figure out what is in it. Processing the data needs to take account of the possibility that the
last data item in the buffer following a read operation may be incomplete — part of a double or long value
or part of a string. The essence of this approach is therefore as follows:
1. Read from the file into a buffer.
2. Extract the string length, the string, and the binary prime value from the buffer repeatedly until no
more complete sets of values are available.
3. Shift any bytes that are left over in the buffer back to the beginning of the buffer. These are some
part of a complete set of the string length, the string, and the binary prime value. Go back to point 1 to
read more from the file.
The buffer classes provide the compact() method for performing the operation you need in the third step
here to shift the bytes that are left over in the buffer back to the beginning. An illustration of the action of
the compact() method on a buffer is shown in Figure 11-2 .
FIGURE 11-2
As you can see, the compacting operation copies everything in the buffer, which are the data elements
from the buffer's current position, up to but not including the buffer's limit, to the beginning of the buffer.
The buffer's position is then set to the element following the last element that was copied, and the limit is
 
 
Search WWH ::




Custom Search