Gets byte array from a ByteBuffer in java

前端 未结 6 707
庸人自扰
庸人自扰 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:03

    Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

    I.e.

    byte[] test = "Hello World".getBytes("Latin1");
    ByteBuffer b1 = ByteBuffer.wrap(test);
    byte[] hello = new byte[6];
    b1.get(hello); // "Hello "
    ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
    byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
    byte[] world = new byte[5];
    b2.get(world); // world = "World"
    

    Which might not be what you intend to do.

    If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

提交回复
热议问题