I/O and Networking with java.nio
Java 1.4 introduced an entirely new API for
high-performance, nonblocking I/O and networking. This API consists
primarily of three new packages.
java.nio
defines
Buffer
classes that are used to store sequences of
bytes or other primitive values.
java.nio.channels
defines
channels
through which data can be transferred between a buffer and a data
source or sink, such as a file or a network socket. This package also
contains important classes used for nonblocking I/O.
Finally, the
java.nio.charset
package contains classes for
efficiently converting buffers of
bytes into buffers of
characters.
The sections that follow contain examples of using all three of these
packages as well as examples of specific I/O tasks with the New I/O
API.
Basic Buffer Operations
The java.nio
package
includes an
abstract Buffer
class, which defines generic
operations on buffers. This package also defines type-specific
subclasses such as ByteBuffer
,
CharBuffer
, and IntBuffer
. (See
Buffer
and ByteBuffer
in the
reference section for details on these classes and their various
methods.) The following code illustrates typical sequences of buffer
operations on a ByteBuffer
. The other
type-specific buffer classes have similar methods.
import java.nio.*; // Buffers don't have public constructors. They are allocated instead. ByteBuffer b = ByteBuffer.allocate(4096); // Create a buffer for 4,096 bytes // Or do this to try to get an efficient buffer from the low-level OS ByteBuffer ...
Get Java in a Nutshell, 5th Edition 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.