Java ByteBuffer to String

后端 未结 10 1605
一生所求
一生所求 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题