The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Byte Buffers  [8 examples]

e163. Creating a Non-Byte Java Type Buffer on a ByteBuffer

You can create views on a ByteBuffer to support buffers of other Java primitive types. For example, by creating a character view on a ByteBuffer, you treat the ByteBuffer like a buffer of characters. The character buffer supports strings directly. Also, hasRemaining() properly works with characters rather than with bytes.

When you create a typed view, it is important to be aware that it is created on top of the bytes between position and limit. That is, the capacity of the new view is (limit - position). The limit of the new view may be reduced so that the capacity is an integral value based on the size of the type. Finally, the view shares the same storage as the underlying ByteBuffer, so any changes to the byte buffer will be seen by the view and visa versa. However, changes to a view's position or limit do not affect the ByteBuffer's properties and visa versa.

    // Obtain a ByteBuffer; see also e158 Creating a ByteBuffer
    ByteBuffer buf = ByteBuffer.allocate(15);
    // remaining = 15
    
    // Create a character ByteBuffer
    CharBuffer cbuf = buf.asCharBuffer();
    // remaining = 7
    
    // Create a short ByteBuffer
    ShortBuffer sbuf = buf.asShortBuffer();
    // remaining = 7
    
    // Create an integer ByteBuffer
    IntBuffer ibuf = buf.asIntBuffer();
    // remaining = 3
    
    // Create a long ByteBuffer
    LongBuffer lbuf = buf.asLongBuffer();
    // remaining = 1
    
    // Create a float ByteBuffer
    FloatBuffer fbuf = buf.asFloatBuffer();
    // remaining = 3
    
    // Create a double ByteBuffer
    DoubleBuffer dbuf = buf.asDoubleBuffer();
    // remaining = 1

 Related Examples
e158. Creating a ByteBuffer
e159. Getting Bytes from a ByteBuffer
e160. Putting Bytes into a ByteBuffer
e161. Converting Between a ByteBuffer an a Byte Array
e162. Getting and Setting Non-Byte Java Types in a ByteBuffer
e164. Using a ByteBuffer to Store Strings
e165. Setting the Byte Ordering for a ByteBuffer

See also: File Locking    Files    Sockets    Streams   


© 2002 Addison-Wesley.