解码将bytebuffer转换为在java中不起作用的字符串
在运行时,我从设备获取字节缓冲数据,我试图解码该数据以读取其内容
当我使用字符串打印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);
一切都返回空数据
解码字节缓冲区数据的方法是什么
# 1 楼答案
缓冲区使用起来有点棘手,因为它们有一个当前状态,在访问它们时需要考虑这个状态
你想把
在每次解码之前,将缓冲区置于您希望解码读取的状态
例如
# 2 楼答案
HeapByteBuffer
的^{换句话说,它会回来
显示字节缓冲区的位置、限制和容量
在这种情况下,您的
ByteBuffer
还有3个字节的容量。每个Charset#decode
调用都会使用ByteBuffer
而您不需要rewind/reset它,因此后续调用没有更多的字节可使用。换句话说,所有这些字符串都将为空# 3 楼答案
您可以这样做:
或
Here是受支持的字符集列表