The Java Developers Almanac 1.4


Order this book from Amazon.

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

e161. Converting Between a ByteBuffer an a Byte Array

    // Create a ByteBuffer from a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    
    // Retrieve bytes between the position and limit
    // (see e160 Putting Bytes into a ByteBuffer)
    bytes = new byte[buf.remaining()];
    buf.get(bytes, 0, bytes.length);
    
    // Retrieve all bytes in the buffer
    buf.clear();
    bytes = new byte[buf.capacity()];
    buf.get(bytes, 0, bytes.length);

 Related Examples
e158. Creating a ByteBuffer
e159. Getting Bytes from a ByteBuffer
e160. Putting Bytes into a ByteBuffer
e162. Getting and Setting Non-Byte Java Types in a ByteBuffer
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.