How to extract used byte array 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 am having some problems.

I have a ByteBuffer that I allocate as some size and then I paste the data into it.

ByteBuffer oldBuffer = ByteBuffer.allocate(SIZE);
addHeader(oldBuffer, pendingItems);
newBuffer.flip();
oldBuffer.put(newBuffer);
// as of now I am sending everything from oldBuffer
send(address, oldBuffer.array());

How can I just send what is used in oldBuffer. Is there one liner for this?

+4
source share
2 answers

You can flip the buffer and then create a new array with the remaining buffer size and fill it.

oldBuffer.flip();
byte[] remaining = new byte[oldBuffer.remaining()];
oldBuffer.get(remaining);

Another way in one liner with flip()and Arrays.copyOf

oldBuffer.flip();
Arrays.copyOf(oldBuffer.array(), oldBuffer.remaining());

And without flip()

Arrays.copyOf(oldBuffer.array(), oldBuffer.position());

, EJP, send(..), send() .

+4

position() .

.

0 , . rewind() .

get(), .

byte[] data = new byte[buffer.position()];
buffer.rewind();
buffer.get(data);

, buffer.array() , buffer.hasArray() true. hasArray(), . buffer.array() .

  1. UnsupportedOperationException - .
  2. ReadOnlyBufferException - .
0
source

Source: https://habr.com/ru/post/1694885/


All Articles