Java Reference
In-Depth Information
The second key difference between streams and channels/buffers is that channels and
buffers tend to support both reading and writing on the same object. This isn't always
true. For instance, a channel that points to a file on a CD-ROM can be read but not
written. A channel connected to a socket that has shutdown input could be written but
not read. If you try to write to a read-only channel or read from a write-only channel,
an UnsupportedOperationException will be thrown. However, more often than not
network programs can read from and write to the same channels.
Without worrying too much about the underlying details (which can vary hugely from
one implementation to the next, mostly as a result of being tuned very closely to the
host operating system and hardware), you can think of a buffer as a fixed-size list of
elements of a particular, normally primitive data type, like an array. However, it's not
necessarily an array behind the scenes. Sometimes it is; sometimes it isn't. There are
specific subclasses of Buffer for all of Java's primitive data types except boolean: Byte
Buffer , CharBuffer , ShortBuffer , IntBuffer , LongBuffer , FloatBuffer , and Double
Buffer . The methods in each subclass have appropriately typed return values and ar‐
gument lists. For example, the DoubleBuffer class has methods to put and get double s.
The IntBuffer class has methods to put and get int s. The common Buffer superclass
only provides methods that don't need to know the type of the data the buffer contains.
(The lack of primitive-aware generics really hurts here.) Network programs use Byte
Buffer almost exclusively, although occasionally one program might use a view that
overlays the ByteBuffer with one of the other types.
Besides its list of data, each buffer tracks four key pieces of information. All buffers have
the same methods to set and get these values, regardless of the buffer's type:
position
The next location in the buffer that will be read from or written to. This starts
counting at 0 and has a maximum value equal to the size of the buffer. It can be set
or gotten with these two methods:
public final int position ()
public final Buffer position ( int newPosition )
capacity
The maximum number of elements the buffer can hold. This is set when the buffer
is created and cannot be changed thereafter. It can be read with this method:
public final int capacity ()
limit
The end of accessible data in the buffer. You cannot write or read at or past this
point without changing the limit, even if the buffer has more capacity. It is set and
gotten with these two methods:
public final int limit ()
public final Buffer limit ( int newLimit )
Search WWH ::




Custom Search