The Java Developers Almanac 1.4


Order this book from Amazon.

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

e164. Using a ByteBuffer to Store Strings

This example demonstrates how to use a ByteBuffer to store characters. For example, an application may want to store strings in a file to avoid the conversion to and from bytes. The example creates a character view on the ByteBuffer that provides methods for reading and writing strings.

This example does not convert characters and bytes. For an example on how to convert characters to and from bytes, see e186 Converting Between Strings (Unicode) and Other Character Set Encodings.

    // Obtain a ByteBuffer; see also e158 Creating a ByteBuffer
    ByteBuffer buf = ByteBuffer.allocate(100);
    
    // Create a character ByteBuffer
    CharBuffer cbuf = buf.asCharBuffer();
    
    // Write a string
    cbuf.put("a string");
    
    // Convert character ByteBuffer to a string.
    // Uses characters between current position and limit so flip it first
    cbuf.flip();
    String s = cbuf.toString();  // a string
    // Does not affect position
    
    // Get a substring
    int start = 2; // start is relative to cbuf's current position
    int end = 5;
    CharSequence sub = cbuf.subSequence(start, end); // str

 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
e163. Creating a Non-Byte Java Type Buffer on a ByteBuffer
e165. Setting the Byte Ordering for a ByteBuffer

See also: File Locking    Files    Sockets    Streams   


© 2002 Addison-Wesley.