Java ByteBuffer to String

后端 未结 10 1570
一生所求
一生所求 2020-12-07 21:30

Is this a correct approach to convert ByteBuffer to String in this way,

String k = \"abcd\";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new Str         


        
相关标签:
10条回答
  • 2020-12-07 22:18

    Here is a simple function for converting a byte buffer to string:

    public String byteBufferToString(ByteBuffer bufferData) {
        byte[] buffer = new byte[bufferData.readableByteCount()];
        // read bufferData and insert into buffer 
        data.read(buffer);
        // CharsetUtil supports UTF_16, ASCII, and many more
        String text = new String(buffer, CharsetUtil.UTF_8);
        System.out.println("Text: "+text);
        return text;
    }
    
    0 讨论(0)
  • 2020-12-07 22:22

    The answers referring to simply calling array() are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

    if (myByteBuffer.hasArray()) {
        return new String(myByteBuffer.array(),
            myByteBuffer.arrayOffset() + myByteBuffer.position(),
            myByteBuffer.remaining());
    } else {
        final byte[] b = new byte[myByteBuffer.remaining()];
        myByteBuffer.duplicate().get(b);
        return new String(b);
    }
    

    For the concerns related to encoding, see Andy Thomas' answer.

    0 讨论(0)
  • 2020-12-07 22:25

    Try this:

    new String(bytebuffer.array(), "ASCII");
    

    NB. you can't correctly convert a byte array to a String without knowing its encoding.

    I hope this helps

    0 讨论(0)
  • 2020-12-07 22:25

    Notice (aside from the encoding issue) that some of the more complicated code linked goes to the trouble of getting the "active" portion of the ByteBuffer in question (for example by using position and limit), rather than simply encoding all of the bytes in the entire backing array (as many of the examples in these answers do).

    0 讨论(0)
提交回复
热议问题