Java Reference
In-Depth Information
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, since operations with the view buffer will not
update the position for the backing byte buffer. We could do what the previous code fragment does
using view buffers:
ByteBuffer buf = ByteBuffer.allocate(50); // The original byte buffer
String text = "Value of e";
// Create view buffer
CharBuffer charBuf = buf.asCharBuffer();
// Transfer string via view buffer
charBuf.put(text);
// Update byte buffer position by the number of bytes we have transferred
buf.position(buf.position() + 2*charBuf.position());
// Transfer binary double value
buf.putDouble(Math.E);
Putting data into a view buffer with a relative
put
operation only updates the position of the view
buffer. The position for the backing
ByteBuffer
is unchanged, so we must increment it to account for
the number of bytes occupied by the Unicode characters we have written. Since we transfer the eight
bytes for the constant
Math.E
directly using
buf
, the position will be incremented by 8 automatically.
Preparing a Buffer for Output to a File
We have seen that a buffer starts out with a position set to 0 - the first element position - and with its
limit set to the capacity. Suppose we create a buffer with the statement:
ByteBuffer buf = ByteBuffer.allocate(80);
We can now create a view buffer that can store values of type
double
with the statement:
DoubleBuffer doubleBuf = buf.asDoubleBuffer();
The view buffer's initial state will be as shown below:
capacity = 10
empty
empty
empty
empty
element
element
element
element
element
element
position = 0
limit = 10