The Java Developers Almanac 1.4


Order this book from Amazon.

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

e162. Getting and Setting Non-Byte Java Types in a ByteBuffer

The ByteBuffer class provides convenience methods for getting and putting other multibyte Java primitive types. There are two issues to be aware of when using these methods. First, ensure that values will be stored using the desired byte ordering; see e165 Setting the Byte Ordering for a ByteBuffer for more information. Second, the hasRemaining() method cannot be used to determine if the buffer has room for a multibyte put. If your application needs to know this information, see e163 Creating a Non-Byte Java Type Buffer on a ByteBuffer for an example that can provide this information.
    // Obtain a ByteBuffer; see also e158 Creating a ByteBuffer
    ByteBuffer buf = ByteBuffer.allocate(100);
    
    // Put values of different types
    buf.putChar((char)123);
    buf.putShort((short)123);
    buf.putInt(123);
    buf.putLong(123L);
    buf.putFloat(12.3F);
    buf.putDouble(12.3D);
    
    // Reset position for reading
    buf.flip();
    
    // Retrieve the values
    char c = buf.getChar();
    short s = buf.getShort();
    int i = buf.getInt();
    long l = buf.getLong();
    float f = buf.getFloat();
    double d = buf.getDouble();

 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
e163. Creating a Non-Byte Java Type Buffer on 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.