在Java中将ByteBuffer转换为字符串无法正常工作

3

我将从设备中获取一个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); 

所有数据都返回空值。

如何解码字节缓冲区数据?


paramByteBuffer是什么?里面包含了什么内容? - Sotirios Delimanolis
这是一个字节缓冲区数据,但不确定格式。 - Harry
3个回答

6
您可以像这样做:

您可以这样操作:

String val = new String(paramByteBuffer.array());

或者

String val = new String(paramByteBuffer.array(),"UTF-8");

这里提供了一个支持的字符集列表


6
缓冲区使用起来有些棘手,因为它们具有当前状态,访问时需要考虑到这一点。
你想要放置
 paramByteBuffer.flip();

在每次解码之前,可以将缓冲区设置为解码所需的状态。

例如:

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);

仍然返回一些垃圾符号。 - Harry
你应该预料到这一点。不同的字符集对于每个字符都有不同的值。 - BevynQ
你需要知道数据使用了哪种字符集进行编码。 - BevynQ

1

toString 方法是 HeapByteBuffer 类的一个方法,它的作用是返回一个字符串,该字符串总结了此缓冲区的状态。

换句话说,它返回

请注意保留原文中的html标签。

java.nio.HeapByteBuffer[pos=0 lim=3 cap=3]

这显示了字节缓冲区的位置、限制和容量。

在这种情况下,你的ByteBuffer还可以容纳3个字节。每个Charset#decode调用都会消耗ByteBuffer,而你没有倒回/重置它,因此后续调用中没有更多的字节可供使用。换句话说,所有这些字符串都将为空。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接