Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 983
Verhogen Avatar asked May 08 '14 20:05

Verhogen


People also ask

What is the use of ByteBuffer in Java?

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.

How do you write and read from ByteBuffer in Java?

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.


1 Answers

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
   }
}
like image 174
Jon Skeet Avatar answered Oct 01 '22 16:10

Jon Skeet