Extract String from ReadOnly java.nio.ByteBuffer

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.

Jon Skeet
people
quotationmark

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
   }
}

people

See more on this question at Stackoverflow