How to extract used byte array from ByteBuffer?

The java.nio.ByteBuffer class has a ByteBuffer.array() method, however this returns an array that is the size of the buffer’s capacity, and not the used capacity. Due to this, I’m having some issues.

I have a ByteBuffer which I am allocating as some size and then I am inserting data to 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 being used in oldBuffer. Is there any one liner to do this?

Solution:

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

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

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

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

And without flip()

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

Also like EJP said, if you have access to the send(..) method, you can add a size and offset argument to the send() method, and avoid the need to create and fill a new array.