Java Reference
In-Depth Information
The channel interfaces all extend a common interface,
java.nio.channels.Channel
, which declares two
methods:
• The
close()
method, which closes a channel
• The
isOpen()
method, which tests the state of the channel, returning
true
if it is open and
false
otherwise
Because the channel interfaces all extend the
AutoCloseable
interface, all channel objects can be closed
automatically if you create them in a
try
block with resources. The methods that each channel interface in
the hierarchy declares are as follows:
ReadableByteChannel
interface:
•
int read(ByteBuffer input)
: Reads bytes from a channel into the
input
buffer and returns
the number of bytes read, or −1 if the end of the stream is reached.
WritableByteChannel
interface:
•
int write(ByteBuffer output)
: Writes bytes from the
output
buffer to the channel and returns
the number of bytes written.
•
ByteChannel
interface: This interface just inherits methods from the
ReadableByteChannel
and
WritableByteChannel
interfaces. No additional methods are declared.
SeekableByteChannel
interface:
•
long position()
: Returns the current position for the channel that corresponds to the current file
position.
•
SeekableByteChannel position(long new))
: Sets the channel's position and thus the position
in the file to
new
.
•
int read(ByteBuffer buf)
: Reads bytes from the channel into
buf
and returns the number of
bytes read, or −1 if the channel has reached the end of the stream.
•
int write(ByteBuffer buf)
: Writes the contents of
buf
to the channel and returns the number
of bytes written.
•
SeekableByteChannel truncate(long size)
: Truncates the file to which the channel is con-
nected to
size
bytes and returns a reference to the channel to permit chaining method calls. If
size
is greater than the current size then the file is not modified.
•
long size()
: Returns the number of bytes in the file to which the channel is attached.
ScatteringByteChannel
interface:
•
int read(ByteBuffer[] inputs)
: Reads bytes from the channel into the array of buffers
in-
puts
and returns the number of bytes read or −1 if the end of the stream is reached.
•
int read(ByteBuffer[] inputs, int offset, int length)
: Reads bytes from the channel
into
length
buffers from the array
inputs
starting with the buffer
inputs[offset].
GatheringByteChannel
interface:
•
int write(ByteBuffer[] outputs)
: Writes bytes from the array of buffers
outputs
to the
channel, and returns the number of bytes written.
•
int write(ByteBuffer[] outputs, int offset, int length)
: Writes bytes to the channel
from
length
buffers from the array
outputs
starting with the buffer
outputs[offset].
All of these methods can throw exceptions of one kind or another, and I go into details on these when
you come to apply them. Note that a channel works only with buffers of type
ByteBuffer
. Other kinds of
buffers do exist as you know, but you can't use them directly with the
read()
and
write()
methods for a
channel.