Java Reference
In-Depth Information
Program writes data into a buffer
Channel reads data from a buffer
Buffer
Data Sink
--------------
Data Source
Java Program
Channel
Buffer
Channel writes data into a buffer
Program reads data from a buffer
Figure 9-1.
Interaction between a channel, buffers, a Java program, a data source, and a data sink
Buffers
A buffer is a fixed-length data container. There is a separate buffer type to hold data for each type of primitive value,
except for
boolean
type values. A buffer is an object in your program. You have a separate class to represent each type
of buffer. All buffer classes are inherited from an abstract
Buffer
class. Buffer classes that hold primitive values are as
follows:
ByteBuffer
•
ShortBuffer
•
CharBuffer
•
IntBuffer
•
LongBuffer
•
FloatBuffer
•
DoubleBuffer
An object of an
XxxBuffer
class is used to hold data of the
Xxx
primitive data type. For example, a
ByteBuffer
is used to hold byte values; a
ShortBuffer
is used to hold short values; a
CharBuffer
is used to hold characters,
and so on.
The following are the four important properties of a buffer, which you must understand to use buffers effectively:
•
•
Capacity
•
Position
•
Limit
•
Mark
The capacity of a buffer is the maximum number of elements that it can hold. The capacity of a buffer is fixed
when the buffer is created. You can think of the capacity of a buffer as the length of an array. Once you create an array,
its length is fixed. Similarly, once you create a buffer, its capacity is fixed. However, a buffer is not necessarily backed
by an array. You can check if a buffer is backed by an array by calling its
hasArray()
method that returns
true
if the
buffer is backed by an array. You can get access to the backing array of a buffer by using the
array()
method of the
buffer object. Once you get access to the backing array of a buffer, any changes made to that array will be reflected in
the buffer. A buffer has a
capacity()
method that returns its capacity.