Java Reference
In-Depth Information
It is sometimes useful to be able to fill several buffers from one source. This is called a
scatter
. These two methods accept an array of
ByteBuffer
objects as arguments and fill
each one in turn:
public
final
long
read
(
ByteBuffer
[]
dsts
)
throws
IOException
public
final
long
read
(
ByteBuffer
[]
dsts
,
int
offset
,
int
length
)
throws
IOException
The first variant fills all the buffers. The second method fills
length
buffers, starting
with the one at
offset
.
To fill an array of buffers, just loop while the last buffer in the list has space remaining.
For example:
ByteBuffer
[]
buffers
=
new
ByteBuffer
[
2
];
buffers
[
0
]
=
ByteBuffer
.
allocate
(
1000
);
buffers
[
1
]
=
ByteBuffer
.
allocate
(
1000
);
while
(
buffers
[
1
].
hasRemaining
()
&&
channel
.
read
(
buffers
)
!=
-
1
)
;
Writing
Socket channels have both read and write methods. In general, they are full duplex. In
order to write, simply fill a
ByteBuffer
, flip it, and pass it to one of the write methods,
which drains it while copying the data onto the output—pretty much the reverse of the
reading process.
The basic
write()
method takes a single buffer as an argument:
public
abstract
int
write
(
ByteBuffer
src
)
throws
IOException
As with reads (and unlike
OutputStream
s), this method is not guaranteed to write the
complete contents of the buffer if the channel is nonblocking. Again, however, the
cursor-based nature of buffers enables you to easily call this method again and again
until the buffer is fully drained and the data has been completely written:
while
(
buffer
.
hasRemaining
()
&&
channel
.
write
(
buffer
)
!=
-
1
)
;
It is often useful to be able to write data from several buffers onto one socket. This is
called a
gather
. For example, you might want to store the HTTP header in one buffer
and the HTTP body in another buffer. The implementation might even fill the two
buffers simultaneously using two threads or overlapped I/O. These two methods accept
an array of
ByteBuffer
objects as arguments, and drain each one in turn:
public
final
long
write
(
ByteBuffer
[]
dsts
)
throws
IOException
public
final
long
write
(
ByteBuffer
[]
dsts
,
int
offset
,
int
length
)
throws
IOException
The first variant drains all the buffers. The second method drains
length
buffers, start‐
ing with the one at
offset
.