Chapter 2. Buffers
It’s all relative.
We
begin our sightseeing tour of the java.nio
packages with the Buffer
classes. These classes
are the foundation upon which java.nio
is built.
In this chapter, we’ll take a close look at buffers,
discover the various types, and learn how to use them.
We’ll then see how the java.nio
buffers relate to the channel classes of
java.nio.channels
.
A Buffer
object is a
container for a fixed amount of data. It acts as a holding tank, or
staging area, where data can be stored and later retrieved. Buffers
are filled and drained, as we discussed in Chapter 1. There is one buffer class for each of the
nonboolean primitive data types. Although buffers act upon the
primitive data types they store, buffers have a strong bias toward
bytes. Nonbyte buffers can perform translation to and from bytes
behind the scenes, depending on how the buffer was created.[1]
We’ll examine the implications of data storage
within buffers later in this chapter.
Buffers work hand
in glove with channels. Channels are portals
through which I/O transfers take place, and
buffers are the sources or targets of those data transfers. For
outgoing transfers, data you want to send is placed in a buffer,
which is passed to a channel. For inbound transfers, a channel
deposits data in a buffer you provide. This hand-off of buffers
between cooperating objects (usually objects you write and one or
more Channel
objects) is key to efficient data handling. Channels will be covered ...
Get Java NIO now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.