将bytebuffer转换为不在java

时间:2015-05-21 03:03:53

标签: java decode bytebuffer

在运行时我从设备获取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返回空数据。

解码字节缓冲区数据有哪些方法?

3 个答案:

答案 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)

您可以这样做:

dbms_random.value

OR

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

Here是受支持的字符集列表

答案 2 :(得分:1)

HeapByteBuffer的{​​{3}}方法只是

  

返回一个总结此缓冲区状态的字符串。

换句话说,它会返回

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

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

在这种情况下,您的ByteBuffer可以容纳3个字节。每个Charset#decode来电都会消耗ByteBuffer,而您不会toString / rewind,因此后续调用不再需要消耗的字节数。换句话说,所有这些字符串都将为空。