Java Reference
In-Depth Information
and so on down to the end:
String length: 11 String: prime = 523 Binary value: 523
String length: 11 String: prime = 541 Binary value: 541
EOF reached .
How It Works
We read the file with a relatively straightforward process. On each iteration of the loop that reads the file, we
first read 8 bytes into lengthBuf since this will be the length of the following string as type double .
Knowing the length of the string, we are able to create a second buffer, buf , to accommodate this plus the 8-
byte long value that is the prime in binary. The loop continues until the read operation using lengthBuf
reaches the end-of-file. If we reach EOF while reading data into buf , the program will assert.
Compacting a Buffer
The alternative approach to reading the file that we identified was to read bytes from the file into a large
buffer for efficiency and then figure out what is in it. Processing the data will need to take account of the
possibility that the last data item in the buffer may be incomplete - part of a double or long value or
part of a string. The essence of this approach will therefore be as follows:
1.
Read from the file into the buffer.
2.
Extract the string length, the string, and the binary prime value from the buffer repeatedly
until no more complete values are available.
3.
Shift any bytes that are left over in the buffer back to the beginning of the buffer. These will
be 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 a method, compact() , for performing the operation we need in point 3 here
to shift bytes that are left over back to the beginning. An illustration of the action of the compact()
method on a buffer is shown below.
capacity = 20
position = 8
limit = 17
Buffer before compacting
buf .compact() .....................
Buffer after compacting
limit = 20
position = 9
Compacting a Buffer
Search WWH ::




Custom Search