在运行时我从设备获取bytebuffer数据,我试图解码该数据以读取它的内容。
当我使用字符串打印bytebuffer时,它显示如下,
java.nio.HeapByteBuffer[pos=0 lim=3 cap=3]
我尝试使用以下所有已知格式进行解码,
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(paramByteBuffer);
String text = charBuffer.toString();
System.out.println("UTF-8"+text);
charBuffer = StandardCharsets.UTF_16.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("UTF_16"+text);
charBuffer = StandardCharsets.ISO_8859_1.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("ISO_8859_1"+text);
charBuffer = StandardCharsets.UTF_16BE.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("UTF_16BE"+text);
charBuffer = StandardCharsets.UTF_16LE.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("UTF_16LE"+text);
charBuffer = StandardCharsets.US_ASCII.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("US_ASCII"+text);
Everything返回空数据。
解码字节缓冲区数据有哪些方法?
答案 0 :(得分:5)
缓冲区使用起来有点棘手,因为它们具有当前状态,访问它们时需要考虑这些状态。
你想放
paramByteBuffer.flip();
在每次解码之前将缓冲区置于您想要解码的状态。
e.g。
ByteBuffer paramByteBuffer = ByteBuffer.allocate(100);
paramByteBuffer.put((byte)'a'); // write 'a' at next position(0)
paramByteBuffer.put((byte)'b'); // write 'b' at next position(1)
paramByteBuffer.put((byte)'c'); // write 'c' at next position(2)
// if I try to read now I will read the next byte position(3) which is empty
// so I need to flip the buffer so the next position is at the start
paramByteBuffer.flip();
// we are at position 0 so we can do our read function
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(paramByteBuffer);
String text = charBuffer.toString();
System.out.println("UTF-8" + text);
// because the decoder has read all the written bytes we are back to the
// state (position 3) we had just after we wrote the bytes in the first
// place so we need to flip again
paramByteBuffer.flip();
// we are now at position 0 so we can do our read function
charBuffer = StandardCharsets.UTF_16.decode(paramByteBuffer);
text = charBuffer.toString();
System.out.println("UTF_16"+text);
答案 1 :(得分:4)
答案 2 :(得分:1)