有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解码将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); 

一切都返回空数据

解码字节缓冲区数据的方法是什么


共 (3) 个答案

  1. # 1 楼答案

    缓冲区使用起来有点棘手,因为它们有一个当前状态,在访问它们时需要考虑这个状态

    你想把

     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);
    
  2. # 2 楼答案

    HeapByteBuffer^{}方法很简单

    Returns a string summarizing the state of this buffer.

    换句话说,它会回来

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

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

    在这种情况下,您的ByteBuffer还有3个字节的容量。每个Charset#decode调用都会使用ByteBuffer而您不需要rewind/reset它,因此后续调用没有更多的字节可使用。换句话说,所有这些字符串都将为空

  3. # 3 楼答案

    您可以这样做:

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

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

    Here是受支持的字符集列表