12

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.

Verhogen
  • 27,221
  • 34
  • 90
  • 109

2 Answers2

21

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
   }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130