Java Reference
In-Depth Information
View Buffers
You can use a
ByteBuffer
object to create a buffer of any of the other types we have introduced, that
shares all or part of the memory that the original
ByteBuffer
uses to store data. Such a buffer is
referred to as a
view
buffer
, because it allows you to view the contents of the byte buffer as elements of
another data type. Data is always transferred to or from a file as a series of bytes, but it will typically
consist of data elements of a mix of types other than type
byte
. A view buffer therefore has two
primary uses, for loading data items that are not of type
byte
into a byte buffer prior to writing it to a
file, and accessing data that has been read from a file as elements that are other than type
byte
.
We could create a
view buffer
of type
IntBuffer
from a
ByteBuffer
object like this:
ByteBuffer buf = ByteBuffer.allocate(1024); // Buffer of 1024 bytes capacity
IntBuffer intBuf = buf.asIntBuffer(); // Now create a view buffer
The content of the view buffer,
intBuf
, that we create here will start at the byte buffer's current
position, which in this case is zero since it is newly created. The remaining bytes in
buf
will effectively
be shared with the view buffer. At least, the maximum number of them that is a multiple of 4 will be,
since
intBuf
stores elements of type
int
that require 4 bytes each. The view buffer will have an initial
position of 0, and a capacity and limit of 256. This is because 256 elements of type
int
completely fill
the 1024 bytes remaining in
buf
. If we had allocated
buf
with 1023 bytes, then
intBuf
would have
mapped to 1020 bytes of
buf
, and would have a capacity and limit of 255.
You could now use this view buffer to load the original buffer with values of type
int
. You could then
use the original byte buffer to write the
int
values to a file. As we said at the outset, view buffers have a
similar role when you are reading a file. You would have a primary buffer of type
ByteBuffer
, into
which you read bytes from a file, and then you might access the contents of the
ByteBuffer
through a
view buffer of type
DoubleBuffer
so you can retrieve the data read from the file as type
double
.
The
ByteBuffer
class defines the following methods for creating view buffers:
Method
Description
asCharBuffer()
Returns a reference to a view buffer of type
CharBuffer
.
asShortBuffer()
Returns a reference to a view buffer of type
ShortBuffer
.
asIntBuffer()
Returns a reference to a view buffer of type
IntBuffer
.
asLongBuffer()
Returns a reference to a view buffer of type
LongBuffer
.
asFloatBuffer()
Returns a reference to a view buffer of type
FloatBuffer
.
asDoubleBuffer()
Returns a reference to a view buffer of type
DoubleBuffer
.
asReadOnlyBuffer()
Returns a reference to a read-only view buffer of type
ByteBuffer
.