Java Reference
In-Depth Information
We keep repeating
except for type
boolean
every so often, so we had better address that. The various
types of buffers only provide for the numerical data types and type
boolean
does not fit into this
category. Of course, you may actually want to record some
boolean
values in a file. In this case, you
have to devise a suitable alternative representation. You could use integer values
0
and
1
, or perhaps
strings "
true"
and "
false"
, or even characters '
t'
and '
f'
. You could even represent a
boolean
value as a single bit and pack eight of them at a time into a single byte, but this is only likely to be
worthwhile if you have a lot of them. Which approach you choose will depend on what is most
convenient in the context in which you are using them.
While we have seven different classes defining buffers, a channel only uses buffers of type
ByteBuffer
to read or write data. The other types of buffers in the table above are called
view buffers
, because they
are usually created as views of an existing buffer of type
ByteBuffer
. We will see how and why a little
later in this chapter.
Buffer Capacity
Each type of buffer stores
elements
of a specific kind - a
ByteBuffer
object holds bytes, a
LongBuffer
object holds integers of type
long
, and so on for the other buffer types. The
capacity
of a
buffer is the maximum number of
elements
it can contain, not the number of
bytes
- unless, of course, it
stores elements of type
byte
. The capacity of a buffer is fixed when you create it and cannot be
changed subsequently. You can obtain the capacity for a buffer object as a value of type
int
by calling
the
capacity()
method that it inherits from the
Buffer
class.