|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(2) Starting from the simplest and building up to the most complex, the first improvement to mention is the set of Buffer classes found in the Java.nio package. These buffers provide a mechanism to store a set of primitive data elements in an in-memory container. Basically, imagine wrapping a combined DataInputStream/DataOutputStream around a fixed-size byte array and then only being able to read and write one data type, like char, int, or double. There are seven sUCh buffers available: ByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer
The ByteBuffer actually supports reading and writing the other six types, but the others are type specific. To demonstrate the use of a buffer, the following snippet converts a String to a CharBuffer and reads a character at a time. You convert the String to a CharBuffer with the wrap method, then get each letter with the get method. CharBuffer buff = CharBuffer.wrap(args[0]);for (int i=0, n=buff.length(); i<n; i++) {System.out.println(buff.get());}When using buffers, it is important to realize there are different sizing and positioning values to worry about. The length method is actually non-standard, specific to CharBuffer. There is nothing wrong with it, but it really reports the remaining length, so if the position is not at the beginning, the reported length will not be the buffer length, but the number of remaining characters within the buffer. In other Words, the above loop can also be written as follows. CharBuffer buff = CharBuffer.wrap(args[0]);for (int i=0; buff.length() > 0; i++) {System.out.println(buff.get());}
|