How do you retrieve a String from a ByteBuffer read-only? I cannot use the ByteBuffer.array () method because it throws a ReadOnlyException. Should I use ByteBuffer.get (arr []) and copy it to read data and create a string? It seems wasteful to create a copy, just to read it.
You can use Charset.decode(ByteBuffer) , which converts ByteBuffer to CharBuffer . Then just call toString() . Code example:
Charset.decode(ByteBuffer)
ByteBuffer
CharBuffer
toString()
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 } }
The ReadOnly buffer cannot give you access to the array, otherwise you can change it. Note. The string has another copy as char []. If this is a concern, I would consider using a read-only buffer.