Java Reference
In-Depth Information
Buffer classes also have
absolute
methods that fill and drain at specific positions within
the buffer without updating the position. For example,
ByteBuffer
has these two:
public
abstract
byte
get
(
int
index
)
public
abstract
ByteBuffer
put
(
int
index
,
byte
b
)
These both throw an
IndexOutOfBoundsException
if you try to access a position at or
past the limit of the buffer. For example, using absolute methods, you can put the same
text into a buffer like this:
CharBuffer
buffer
=
CharBuffer
.
allocate
(
12
);
buffer
.
put
(
0
,
'H'
);
buffer
.
put
(
1
,
'e'
);
buffer
.
put
(
2
,
'l'
);
buffer
.
put
(
3
,
'l'
);
buffer
.
put
(
4
,
'o'
);
However, you no longer need to flip before reading it out, because the absolute methods
don't change the position. Furthermore, order no longer matters. This produces the
same end result:
CharBuffer
buffer
=
CharBuffer
.
allocate
(
12
);
buffer
.
put
(
1
,
'e'
);
buffer
.
put
(
4
,
'o'
);
buffer
.
put
(
0
,
'H'
);
buffer
.
put
(
3
,
'l'
);
buffer
.
put
(
2
,
'l'
);
Bulk Methods
Even with buffers, it's often faster to work with blocks of data rather than filling and
draining one element at a time. The different buffer classes have bulk methods that fill
and drain an array of their element type.
For example,
ByteBuffer
has
put()
and
get()
methods that fill and drain a
ByteBuff
er
from a preexisting byte array or subarray:
public
ByteBuffer
get
(
byte
[]
dst
,
int
offset
,
int
length
)
public
ByteBuffer
get
(
byte
[]
dst
)
public
ByteBuffer
put
(
byte
[]
array
,
int
offset
,
int
length
)
public
ByteBuffer
put
(
byte
[]
array
)
These
put
methods insert the data from the specified array or subarray, beginning at
the current position. The get methods read the data into the argument array or subarray
beginning at the current position. Both
put
and
get
increment the position by the length
of the array or subarray. The
put
methods throw a
BufferOverflowException
if the
buffer does not have sufficient space for the array or subarray. The
get
methods throw
a
BufferUnderflowException
if the buffer does not have enough data remaining to fill
the array or subarrray. These are runtime exceptions.