0

假设我有 2 个 ByteBuffer ,其中包含一些字节......如何将一个 ByteBuffer 的所有内容与另一个追加?我正在这样做,但它会引发 BufferUnderFlowException:

ByteBuffer allData = ByteBuffer.allocate(999999);
ByteBuffer buff = null;
for (int i = 0; i < n; i++) {
    buff = aMethodThatReturnsAFilledByteBuffer();
    allData.put(buff);
}

我做错了什么?提前致谢。

4

2 回答 2

2

它是如何工作的:

ByteBuffer.allocate(byteBuffer.limit() + byteBuffer2.limit())
          .put(byteBuffer)
          .put(byteBuffer2)
          .rewind()

在这里使用 bytebuffer limit(),因为这是填充 byteBuffers 的地方。使用 capacity() 也应该有效,但可以分配比您严格需要的更多字节。

对于限制和容量,我查看了这篇文章:ByteBuffer 中的限制和容量有什么区别?

于 2019-03-08T13:38:34.040 回答
0

You need to flip() the source buffer prior to any operating that implies a get() operation, such as a write(), or using it as the source of a put() operation into another buffer. You also need to compact() it afterwards to restore its state.

于 2012-06-02T02:08:11.583 回答