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.
ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.
The methods get() and put() read and write a byte respectively at the current position and then automatically update the position. Thus, in the simplest case of just wanting to read sequentially through data in the buffer (or write data sequentially), this can be accomplished with some extremely straightforward code.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With