Java Reference
In-Depth Information
The
java.nio
package expands the networking capabilities of the language with classes
useful for reading and writing data; working with files, sockets, and memory; and han-
dling text.
Two related packages also are used often when you are working with the new input/
output features:
java.nio.channels
and
java.nio.charset
.
Buffers
The
java.nio
package includes support for
buffers
, objects that represent data streams
stored in memory.
Buffers are often used to improve the performance of programs that read input or write
output. They enable a program to put a lot of data in memory, where it can be read, writ-
ten, and modified more quickly.
17
A buffer corresponds with each of the primitive data types in Java:
n
ByteBuffer
n
CharBuffer
n
DoubleBuffer
n
FloatBuffer
n
IntBuffer
n
LongBuffer
n
ShortBuffer
Each of these classes has a static method called
wrap()
that can be used to create a
buffer from an array of the corresponding data type. The only argument to the method
should be the array.
For example, the following statements create an array of integers and an
IntBuffer
that
holds the integers in memory as a buffer:
int[] temperatures = { 90, 85, 87, 78, 80, 75, 70, 79, 85, 92, 99 };
IntBuffer tempBuffer = IntBuffer.wrap(temperatures);
A buffer keeps track of how it is used, storing the position where the next item will be
read or written. After the buffer is created, its
get()
method reads the data at the current