假设我有2个包含一些字节的ByteBuffer ...如何将一个ByteBuffer的所有内容追加到其他内容的最佳方法是什么?我这样做但它抛出一个BufferUnderFlowException:
ByteBuffer allData = ByteBuffer.allocate(999999);
ByteBuffer buff = null;
for (int i = 0; i < n; i++) {
buff = aMethodThatReturnsAFilledByteBuffer();
allData.put(buff);
}
我做错了什么?提前致谢。
你需要在任何暗示flip()
操作的操作之前get()
源缓冲区,例如write()
,或者使用它作为put()
操作到另一个缓冲区的源。你还需要compact()
它后来恢复其状态。
它是如何工作的:
ByteBuffer.allocate(byteBuffer.limit() + byteBuffer2.limit())
.put(byteBuffer)
.put(byteBuffer2)
.rewind())