Java Reference
In-Depth Information
buf.flip();
}
strChars = new byte[2*strLength];
// Array for string bytes
buf.get(strChars);
// Get the bytes
if(buf.remaining()<8) {
// Verify enough bytes for
prime value
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the binary prime
value.");
break;
// EOF reached
}
buf.flip();
}
System.out.printf(
"String length: %3s String: %-12s Binary
Value: %3d%n",
strLength,
ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong());
}
System.out.println("\nEOF reached.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
ReadPrimesMixedData2.java
This should result in the same output as the previous example.
How It Works
I chose a buffer size that would guarantee that we do multiple read operations to read the complete file
contents and that we would get bits of a complete record left at the end of the buffer.
All the work is done in the indefinite while loop. Before the loop executes you create a direct buffer
with a capacity of 256 bytes by calling the allocateDirect() method. A direct buffer is faster if you
are reading a lot of data from a file, as the data is transferred directly from the file to our buffer. The code
within the loop determines whether there are data values left in the buffer by calling the remaining()
method for the buffer object. You only do another file read when you have processed all the complete
prime records that the buffer contains. This is when remaining() returns a value that is less than the
number of bytes needed to accommodate the next data item. The default initial settings for the buffer are
with the position at zero and the limit at the capacity, and this would suggest falsely that there is data in
the buffer. Therefore you set the position to the limit initially so that the remaining() method returns
zero at the beginning of the first loop iteration.
Within the loop you first check whether there are sufficient bytes for the double value that specifies the
string length. On the first iteration, this is definitely not the case, so the compact() method is called to
Search WWH ::




Custom Search