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
?
Consider reading the API page for ByteBuffer .
ByteBuffer get(byte[])
and
ByteBuffer get(byte[] dst, int offset, int length)
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 (eg 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!
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.