Java Reference
In-Depth Information
sions, — one without a parameter that retrieves the item at the current position and the other with an index
parameter of type
int
that retrieves the item at the specified position.
Using View Buffers
View buffers are intended to make it easier to transfer data elements of various basic types to or from a
ByteBuffer
. The only slightly tricky part is that you have to keep track of the position for the original
ByteBuffer
object yourself when you use a view buffer because operations with the view buffer do not up-
date the position for the backing byte buffer. You could do what the previous code fragment does using view
buffers:
String text = "Value of e";
ByteBuffer buf = ByteBuffer.allocate(50); // The original byte buffer
CharBuffer charBuf = buf.asCharBuffer(); // Create view buffer
charBuf.put(text); // Transfer string via view buffer
// Update byte buffer position by the number of bytes we have transferred
buf.position(buf.position() + 2*charBuf.position());
buf.putDouble(Math.E); // Transfer binary double value
Putting data into a view buffer with a relative
put()
operation updates only the position of the view
buffer. The position for the backing
ByteBuffer
is unchanged, so you must increment it to account for the
number of bytes occupied by the Unicode characters that you have written. Because you transfer the eight
bytes for the constant
Math.E
directly using
buf
, the position in
buf
is incremented by 8 automatically. Of
course, it's essential that you update the buffer's position to account for the characters you have transferred
before you transfer the floating-point value. If you don't, you overwrite the first 8 bytes of the character
data.
Preparing a Buffer for Output to a File
You have seen that a buffer starts out with its position set to 0 — the first element position — and with its
limit set to the capacity. The state of a view buffer reflects the state of the byte buffer from which it is cre-
ated. Suppose you create a byte buffer with the following statement:
ByteBuffer buf = ByteBuffer.allocate(80);
You can now create a view buffer from this byte buffer that you can use to store values of type
double
with the statement:
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
The view buffer's initial state is shown in
Figure 10-7
.