Gets byte array from a ByteBuffer in java

前端 未结 6 711
庸人自扰
庸人自扰 2020-11-30 01:31

Is this the recommended way to get the bytes from the ByteBuffer

ByteBuffer bb =..

byte[] b = new byte[bb.remaining()]
bb.get(b, 0, b.length);
6条回答
  •  执笔经年
    2020-11-30 02:18

    final ByteBuffer buffer;
    if (buffer.hasArray()) {
        final byte[] array = buffer.array();
        final int arrayOffset = buffer.arrayOffset();
        return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
                                  arrayOffset + buffer.limit());
    }
    // do something else
    

提交回复
热议问题