Question

Whilst the ByteBuffer.put(ByteBuffer) method is present, ByteBuffer.get(ByteBuffer) seems to be missing? How am I supposed to achieve reading a smaller ByteBuffer from a larger ByteBuffer?

Was it helpful?

Solution

There exists the ByteBuffer#put method:

public ByteBuffer put(ByteBuffer src) : This method transfers the bytes remaining in the given source buffer into this buffer

You are looking for something like

public ByteBuffer get(ByteBuffer dst) : This method transfers the bytes remaining in this buffer into the given target buffer

But consider that operations get and put are somewhat symmetric.

ByteBuffer src = ...
ByteBuffer dst = ...
//src.get(dst); // Does not exist
dst.put(src); // Use this instead

You explicitly talked about smaller and larger buffers. So I assume that the dst buffer is smaller than the src buffer. In this case, you can simply set the limit of the source buffer accordingly:

ByteBuffer src = ...
ByteBuffer dst = ...
int oldLimit = src.limit();
src.limit(src.position()+dst.remaining());
dst.put(src);
src.limit(oldLimit);

Alternative formulations are possible (e.g. using a ByteBuffer#slice() of the original buffer). But in any case, you do not have to copy the buffer contents into a new byte array just to transfer it into another buffer!

OTHER TIPS

Consider reading the API page for ByteBuffer.

ByteBuffer get(byte[])

and

ByteBuffer get(byte[] dst, int offset, int length)

If I understand correctly, you just need to re-wrap the byte[] in a new ByteBuffer.

ByteByffer buffer = ...;
byte[] sub = new byte[someSize];
buffer.get(sub [, ..]); // use appropriate get(..) method
buffer = ByteBuffer.wrap(sub);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top