How to get used byte [] from ByteBuffer

The class java.nio.ByteBufferhas a method ByteBuffer.array(), however, it returns an array whose size is equal to the size of the buffer, and not the capacity used. Because of this, I had a lot of problems.

I noticed that using ByteBuffer.remaining()gives me the number of bytes that are currently being used by the buffer, so basically what I'm looking for is a way to get byte[]ONLY used bytes, (i.e. bytes displayed in ByteBuffer.remaining().

I tried several different things, but I seem to fail, the only workaround I can come up with is to create another one ByteBufferwith the remaining buffer size allocated, and then write (x) bytes,

+4
source share
2 answers

From reading Javadocs , I think the rest gives only the number of bytes between the current position and the limit.

rest()

Returns the number of elements between the current position and the limit.

Further

Buffer volume is the number of elements contained in it. The buffer volume is never negative and never changes.

The buffer limit is the index of the first element that cannot be read or written. A buffer limit is never negative and never exceeds its capacity.

The buffer position is the index of the next item to read or write. The buffer position is never negative and never exceeds its limit.

So, keeping in mind that about this:

static byte[] getByteArray(ByteBuffer bb) {
    byte[] ba = new byte[bb.limit()];
    bb.get(ba);
    return ba;
}

This uses the ByteBuffer method. get(byte[] dst)

public ByteBuffer get (byte [] dst)

. . src.get(a) ,

 src.get(a, 0, a.length) 
+4

byte[], ByteBuffer.get(byte[]) ByteBuffer.get(byte[], int, int) . ByteBuffer flip .

ByteBuffer, ...

javadocs .

0

All Articles