Java Reference
In-Depth Information
The limit is automatically set to the capacity, 10, so it points to one element beyond the last element.
We could load six values of type
double
into this buffer with the following statements:
double[] data = { 1.0, 1.414, 1.732, 2.0, 2.236, 2.449 };
doubleBuf.put(data); // Transfer the array elements to the buffer
This operation automatically increments the position for the buffer. Now the buffer will be as shown below:
capacity = 10
empty
empty
empty
empty
1.0
1.414
1.732
2.0
2.236
2.449
position = 0
limit = 10
The position and limit values are now set to values ready for more data to be added to the buffer. The
value of
position
points to the first empty element and
limit
points to one beyond the last empty element.
Of course, the position for the backing
ByteBuffer
is still in its original state, but we can update that
to correspond with the data we have loaded into the view buffer with the statement:
buf.setPosition(8*doubleBuf.getPosition());
If we now want to write the data we have in the buffer to a file, we must change the values for position
and limit in the byte buffer to identify the elements that are to be written. A file write operation will
write data elements starting from the element in the buffer at the index specified by
position
, and up to
and including the element at the index
limit-1
. To write our data to the file, the limit for the byte buffer
needs to be set to the current position, and the position needs to be set back to zero. We could do this
explicitly using the methods we have seen. For instance:
// Limit to current position and position to 0
buf.limit(buf.position()).position(0);
This will first set the limit to the byte referenced by the current position, and then reset the position
back to the first byte, byte 0. However, we don't need to specify the operation in such detail. The
Buffer
class conveniently defines a method,
flip()
, that does exactly this, so you would normally set
up the buffer to be written to a file like this:
// Limit to current position and position to 0
buf.flip();
The
flip()
method returns the buffer reference as type
Buffer
, so you can chain this operation on
the buffer with others in a single statement. So, after you have loaded your byte buffer with data, don't
forget to flip it before you write it to a file. If you don't, your data will not be written to the file, but
garbage may well be. If you loaded the data using a view buffer, you also have to remember to update
the byte buffer's position before performing the flip.