Java Reference
In-Depth Information
If you 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 I said at the outset, view buffers have a sim-
ilar 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
to enable you to retrieve the data that is read from the file as values of type
double
.
The
ByteBuffer
class defines the methods for creating view buffers for a byte buffer object shown in
TABLE 10-6
:
Methods to Create 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
In each case, the view buffer's contents start at the current position of the original byte buffer. The posi-
tion of the view buffer itself is initially set to zero, and its capacity and limit are set to the number of bytes
remaining in the original byte buffer divided by the number of bytes in the type of element that the view
buffer holds.
Figure 10-3
illustrates a view buffer of type
IntBuffer
that is created after the initial position
of the byte buffer has been incremented by 2, possibly after inserting a value of type
char
into the byte buf-
fer.
You can create as many view buffers from a buffer of type
ByteBuffer
as you want, and they can overlap
or not as you require. A view buffer always maps to bytes in the byte buffer starting at the current position.
You frequently want to map several different view buffers to a single byte buffer so that each provides a