The Java Developers Almanac 1.4


Order this book from Amazon.

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

e158. Creating a ByteBuffer

A ByteBuffer is a fixed-capacity buffer that holds byte values. This example demonstrates a number of ways to create a ByteBuffer.

See also e159 Getting Bytes from a ByteBuffer and e160 Putting Bytes into a ByteBuffer.

    // Create a ByteBuffer using a byte array
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    
    // Create a non-direct ByteBuffer with a 10 byte capacity
    // The underlying storage is a byte array.
    buf = ByteBuffer.allocate(10);
    
    // Create a direct (memory-mapped) ByteBuffer with a 10 byte capacity.
    buf = ByteBuffer.allocateDirect(10);
    
    // To create a ByteBuffer for a memory-mapped file,
    // see e166 Creating a Memory-Mapped File

 Related Examples
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
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.