简体   繁体   English

如何从较大的ByteBuffer中读取较小的ByteBuffer?

[英]How can I read a smaller ByteBuffer from a larger ByteBuffer?

Whilst the ByteBuffer.put(ByteBuffer) method is present, ByteBuffer.get(ByteBuffer) seems to be missing? 虽然存在ByteBuffer.put(ByteBuffer)方法,但ByteBuffer.get(ByteBuffer)似乎丢失了? How am I supposed to achieve reading a smaller ByteBuffer from a larger ByteBuffer ? 我怎么实现读取一个较小ByteBuffer从更大ByteBuffer

Consider reading the API page for ByteBuffer . 考虑阅读ByteBufferAPI页面

ByteBuffer get(byte[])

and

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

There exists the ByteBuffer#put method: 存在ByteBuffer#put方法:

public ByteBuffer put(ByteBuffer src) : This method transfers the bytes remaining in the given source buffer into this buffer public ByteBuffer put(ByteBuffer src) :此方法将给定源缓冲区中剩余的字节传输到此缓冲区

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 public ByteBuffer get(ByteBuffer dst) :此方法将此缓冲区中剩余的字节传输到给定的目标缓冲区

But consider that operations get and put are somewhat symmetric. 但是考虑到操作getput有点对称。

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. 所以我假设dst缓冲区小于src缓冲区。 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). 替代配方是可能的(例如,使用原始缓冲区的ByteBuffer#slice() )。 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 . 如果我理解正确,你只需要在新的ByteBuffer重新包装byte[]

ByteByffer buffer = ...;
byte[] sub = new byte[someSize];
buffer.get(sub [, ..]); // use appropriate get(..) method
buffer = ByteBuffer.wrap(sub);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM