The Buffer Zone
While most of the changes in Java 2 Standard Edition Version 1.4 (J2SE 1.4) are relatively minor, programmers who work with input and output received an embarrassment of riches in the form of the java.nio package.
Tuesday, October 15th, 2002
While most of the changes in Java 2 Standard Edition Version 1.4 (J2SE 1.4) are relatively minor, programmers who work with input and output received an embarrassment of riches in the form of the java.nio package.
Java has always supported I/O programming through the java.io package, and java.io continues to be supported in J2SE 1.4. However, there’s considerable benefit to using java.nio:
- Large amounts of primitive data can be accessed and transformed quickly using buffers.
- Files can be read and written using channels, which support file locking, memory mapping, and character set encoding.
- Data can be exchanged over a network more safely with secure sockets and more reliably with socket channels, the first Java networking classes that support non-blocking input and output.
This month and next, we’ll focus on java.nio, starting with buffers.
Buffers
java.nio’s buffers are objects that hold large amounts of data in memory. Each buffer holds a single kind of Java primitive (in a sense, each buffer has a “type”), and maintains its own state, including its maximum capacity and the position of the next read or write.
With the abstract Buffer class at the top of the hierarchy, there is an abstract buffer class for almost all of the primitive data types in Java: ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, and ShortBuffer. (What’s missing? A buffer for Boolean.)
For example, the following code creates an IntBuffer from an array of integers: