Java in a Nutshell, 5th Edition [Electronic resources]

نسخه متنی -صفحه : 1191/ 411
نمايش فراداده

ByteBufferjava.nio

Java 1.4comparable

ByteBuffer holds a sequence of bytes for use in an I/O operation. ByteBuffer is an abstract class, so you cannot instantiate one by calling a constructor. Instead, you must use allocate( ) , allocateDirect( ), or wrap( ).

allocate( ) returns a ByteBuffer with the specified capacity. The position of this new buffer is zero, and its limit is set to its capacity. allocateDirect( ) is like allocate( ) except that it attempts to allocate a buffer that the underlying operating system can use "directly." Such direct buffers" may be substantially more efficient for low-level I/O operations than normal buffers, but may also have significantly larger allocation costs.

If you have already allocated an array of bytes, you can use the wrap( ) method to create a ByteBuffer that uses the byte array as its storage. In the one-argument version of wrap( ) you specify only the array; the buffer capacity and limit are set to the array length, and the position is set to zero. In the other form of wrap( ) you specify the array, as well as an offset and length that specify a portion of that array. The capacity of the resulting ByteBuffer is again set to the total array length, but its position is set to the specified offset, and its limit is set to the offset plus length.

Once you have obtained a ByteBuffer, you can use the various get( ) and put( ) methods to read data from it or write data into it. Several versions of these methods exist to read and write single bytes or arrays of bytes. The single-byte methods come in two forms. Relative get( ) and put( ) methods query or set the byte at the current position and then increment the position. The absolute forms of the methods take an additional arguement that specifies the buffer element that is to be read or written and do not affect the buffer position. Two other relative forms of the get( ) method exist to read as sequence of bytes (starting at and incrementing the buffer's position) into a specified byte array or a specified sub-array. These methods throw a BufferUnderflowException if there are not enough bytes left in the buffer. Two relative forms of the put( ) method copy bytes from a specified array or sub-array into the buffer (starting at and incrementing the buffer's position). They throw a BufferOverflowException if there is not enough room left in the buffer to hold the bytes. One final form of the put( ) method transfers all the remaining bytes from one ByteBuffer into this buffer, incrementing the positions of both buffers.

In addition to the get( ) and put( ) methods, ByteBuffer also defines another operation that affect the buffer's content. compact( ) discards any bytes before the buffer position, and copies all bytes between the position and limit to the beginning of the buffer. The position is then set to the new limit, and the limit is set to the capacity. This method compacts a buffer by discarding elements that have already been read, and then prepares the buffer for appending new elements to those that remain.

All Buffer subclasses, such as CharBuffer, IntBuffer and FloatBuffer have analogous methods which are just like these get( ) and put( ) methods except that they operate on different data types. ByteBuffer is unique among Buffer subclasses in that it has additional methods for reading and writing values of other primitive types from and into the byte buffer. These methods have names like getInt( ) and putChar( ), and there are methods for all primitive types except byte and boolean. Each method reads or writes a single primitive value. Like the get( ) and put( ) methods, they come in relative and absolute variations: the relative methods start with the byte at the buffer's position, and increment the position by the appropriate number of bytes (two bytes for a char, four bytes for an int, eight bytes for a double, etc.). The absolute methods take an buffer index (it is a byte index and is not multiplied by the size of the primitive value) as an argument and do not modify the buffer position. The encoding of multi-byte primitive values into a byte buffer can be done most-significant byte to least-significant byte ("big-endian byte order") or the reverse ("little-endian byte order"). The byte order used by these primitive-type get and put methods is specified by a ByteOrder object. The byte order for a ByteBuffer can be queried and set with the two forms of the order( ) method. The default byte order for all newly-created ByteBuffer objects is ByteOrder.BIG_ENDIAN.

Other methods that are unique to ByteBuffer( ) are a set of methods that allow a buffer of bytes to be viewed as a buffer of other primitive types. asCharBuffer( ), asIntBuffer( ) and related methods return "view buffers" that allow the bytes between the position and the limit of the underlying ByteBuffer to be viewed as a sequence of characters, integers, or other primitive values. The returned buffers have position, limit, and mark values that are independent of those of the underlying buffer. The initial position of the returned buffer is zero, and the limit and capacity are the number of bytes between the position and limit of the original buffer divided by the size in bytes of the relevant primitive type (two for char and short, four for int and float, and eight for long and double). Note that the returned view buffer is a view of the bytes between the position and limit of the byte buffer. Subsequent changes to the position and limit of the byte buffer do not change the size of the view buffer, but changes to the bytes themselves to change the values that are viewed through the view buffer. View buffers use the byte ordering that was current in the byte buffer when they were created; subsequent changes to the byte order of the byte buffer do not affect the view buffer. If the underlying byte buffer is direct, then the returned buffer is also direct; this is important because ByteBuffer is the only buffer class with an allocateDirect( ) method.

ByteBuffer defines some additional methods, which, like the get( ) and put( ) methods have analogs in all Buffer subclasses. duplicate( ) returns a new buffer that shares the content with this one. The two buffers have independent position, limit, and mark values, although the duplicate buffer starts off with the same values as the original buffer. The duplicate buffer is direct if the original is direct and is read-only if the original is read-only. The buffers share content, and content changes made to either buffer are visible through the other. asReadOnlyBuffer( ) is like duplicate( ) except that the returned buffer is read-only, and all of its put( ) and related methods throw a ReadOnlyBufferException. slice( ) is also somewhat like duplicate( ) except the returned buffer represents only the content between the current position and limit. The returned buffer has a position of zero, a limit and capacity equal to the number of remaining elements in this buffer, and an undefined mark. isDirect( ) is a simple method that returns true if a buffer is a direct buffer and false otherwise. If this buffer has a backing array and is not a read-only buffer (e.g., if it was created with the allocate( ) or wrap( ) methods) then hasArray( ) returns TRue, array( ) returns the backing array, and arrayOffset( ) returns the offset within that array of the first element of the buffer. If hasArray( ) returns false, then array( ) and arrayOffset( ) may throw an UnsupportedOperationException or a ReadOnlyBufferException.

Finally, ByteBuffer and other Buffer subclasses override several standard object methods. The equals( ) methods compares the elements between the position and limit of two buffers and returns true only if there are the same number and have the same value. Note that elements before the position of the buffer are not considered. The hashCode( ) method is implemented to match the equals( ) method: the hashcode is based only upon the elements between the position and limit of the buffer. This means that the hashcode changes if either the contents or position of the buffer changes. This means that instances of ByteBuffer and other Buffer subclasses are not usually useful as keys for hashtables or java.util.Map objects. toString( ) returns a string summary of the buffer, but the precise contents of the string are unspecified. ByteBuffer and each of the other Buffer subclasses also implement the Comparable interface and define a compareTo( ) method that performs an element-by-element comparison operation on the buffer elements between the position and the limit of the buffer.

Figure 13-3. java.nio.ByteBuffer

public abstract class

ByteBuffer extends Buffer implements Comparable<ByteBuffer> { // No Constructor // Public Class Methods public static ByteBuffer

allocate (int

capacity ); public static ByteBuffer

allocateDirect (int

capacity ); public static ByteBuffer

wrap (byte[ ]

array ); public static ByteBuffer

wrap (byte[ ]

array , int

offset , int

length ); // Public Instance Methods public final byte[ ]

array ( ); public final int

arrayOffset ( ); public abstract CharBuffer

asCharBuffer ( ); public abstract DoubleBuffer

asDoubleBuffer ( ); public abstract FloatBuffer

asFloatBuffer ( ); public abstract IntBuffer

asIntBuffer ( ); public abstract LongBuffer

asLongBuffer ( ); public abstract ByteBuffer

asReadOnlyBuffer ( ); public abstract ShortBuffer

asShortBuffer ( ); public abstract ByteBuffer

compact ( ); public abstract ByteBuffer

duplicate ( ); public abstract byte

get ( ); public abstract byte

get (int

index ); public ByteBuffer

get (byte[ ]

dst ); public ByteBuffer

get (byte[ ]

dst , int

offset , int

length ); public abstract char

getChar ( ); public abstract char

getChar (int

index ); public abstract double

getDouble ( ); public abstract double

getDouble (int

index ); public abstract float

getFloat ( ); public abstract float

getFloat (int

index ); public abstract int

getInt ( ); public abstract int

getInt (int

index ); public abstract long

getLong ( ); public abstract long

getLong (int

index ); public abstract short

getShort ( ); public abstract short

getShort (int

index ); public final boolean

hasArray ( ); public abstract boolean

isDirect ( ); public final ByteOrder

order ( ); public final ByteBuffer

order (ByteOrder

bo ); public ByteBuffer

put (ByteBuffer

src ); public abstract ByteBuffer

put (byte

b ); public final ByteBuffer

put (byte[ ]

src ); public abstract ByteBuffer

put (int

index , byte

b ); public ByteBuffer

put (byte[ ]

src , int

offset , int

length ); public abstract ByteBuffer

putChar (char

value ); public abstract ByteBuffer

putChar (int

index , char

value ); public abstract ByteBuffer

putDouble (double

value ); public abstract ByteBuffer

putDouble (int

index , double

value ); public abstract ByteBuffer

putFloat (float

value ); public abstract ByteBuffer

putFloat (int

index , float

value ); public abstract ByteBuffer

putInt (int

value ); public abstract ByteBuffer

putInt (int

index , int

value ); public abstract ByteBuffer

putLong (long

value ); public abstract ByteBuffer

putLong (int

index , long

value ); public abstract ByteBuffer

putShort (short

value ); public abstract ByteBuffer

putShort (int

index , short

value ); public abstract ByteBuffer

slice ( ); // Methods Implementing Comparable

5.0 public int

compareTo (ByteBuffer

that ); // Public Methods Overriding Object public boolean

equals (Object

ob ); public int

hashCode ( ); public String

toString ( ); }

Subclasses

MappedByteBuffer

Passed To

Too many methods to list.

Returned By

java.nio.charset.Charset.encode( ), java.nio.charset.CharsetEncoder.encode( )