문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top