Gets byte array from a ByteBuffer in java

前端 未结 6 728
庸人自扰
庸人自扰 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 01:59

    If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

    ByteBuffer byteBuffer = ...;
    byte[] data = new byte[byteBuffer.capacity()];
    ((ByteBuffer) byteBuffer.duplicate().clear()).get(data);
    

提交回复
热议问题