Channels
Channels are defined injava.nio.channels. A channel represents an open connection to an
I/O source or destination. You obtain a channel by callinggetChannel( )on an object that
supports channels. For example,getChannel( )is supported by following I/O classes.
DatagramSocket FileInputStream FileOutputStream
RandomAccessFile Ser verSocket Socket
Thus, to obtain a channel, you first obtain an object of one of these classes and then call
getChannel( )on that object.
The specific type of channel returned depends upon the type of objectgetChannel( )
is called on. For example, when called on aFileInputStream,FileOutputStream,or
RandomAccessFile,getChannel( )returns a channel of typeFileChannel. When called
on aSocket,getChannel( )returns aSocketChannel.
Channels such asFileChannelandSocketChannelsupport variousread( )andwrite( )
methods that enable you to perform I/O operations through the channel. For example,
here are a few of theread( )andwrite( )methods defined forFileChannel. All can throw
anIOException.
Method Description
abstract int read(ByteBufferbb) Reads bytes from the invoking channel intobbuntil the buffer
is full or there is no more input. Returns the number of bytes
actually read.
abstract int read(ByteBufferbb,
longstart)
Beginning at the file location specified bystart,reads bytes
from the invoking channel intobbuntil the buffer is full or
there is no more input. The current position is unchanged.
Returns the number of bytes actually read or –1 ifstartis
beyond the end of the file.
abstract int write(ByteBufferbb) Writes the contents ofbbto the invoking channel, starting
at the current position. Returns the number of bytes written.
abstract int write(ByteBufferbb,
longstart)
Beginning at the file location specified bystart,writes the
contents ofbbto the invoking channel. The current position
is unchanged. Returns the number of bytes written.
All channels support additional methods that give you access to and control over the
channel. For example,FileChannelsupports methods to get or set the current position,
transfer information between file channels, obtain the current size of the channel, and lock
the channel, among others.FileChannelalso provides themap( )method, which lets you
map a file to a buffer.
Charsets and Selectors
Two other entities used by NIO are charsets and selectors. Acharsetdefines the way that
bytes are mapped to characters. You can encode a sequence of characters into bytes using
anencoder.You can decode a sequence of bytes into characters using adecoder.Charsets,
encoders, and decoders are supported by classes defined in thejava.nio.charsetpackage.
818 Part II: The Java Library