x
Loading
 Loading
Hello, Guest | Login | Register

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.

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:

 int[] goals =…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace