Question

How do you extract a String from a read-only ByteBuffer? I can't use the ByteBuffer.array() method because it throws a ReadOnlyException. Do I have to use ByteBuffer.get(arr[]) and copy it out to read the data and create a String? Seems wasteful to have to create a copy just to read it.

Was it helpful?

Solution

You should be able to use Charset.decode(ByteBuffer) which will convert a ByteBuffer to a CharBuffer. Then just call toString() on that. Sample code:

import java.nio.*;
import java.nio.charset.*;

class Test {
   public static void main(String[] args) throws Exception {
       byte[] bytes = { 65, 66 }; // "AB" in ASCII
       ByteBuffer byteBuffer =
           ByteBuffer.wrap(bytes).asReadOnlyBuffer();
       CharBuffer charBuffer = StandardCharsets.US_ASCII.decode(byteBuffer);
       String text = charBuffer.toString();
       System.out.println(text); // AB
   }
}

OTHER TIPS

The ReadOnly buffer can't give you access tot he array, otherwise you might change it. Note: the String has yet another copy as a char[]. If this is a concern I would re-think the use of a read only buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top