0

Suppose that I have 2 ByteBuffer containing some bytes in it... How would be the best way to append all the content of one ByteBuffer with other? I'm doing this but it throws a BufferUnderFlowException:

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

What I'm doing wrong? Thanks in advance.

mevqz
  • 653
  • 3
  • 9
  • 19
  • Have you read the documentation? http://docs.oracle.com/javase/1.5.0/docs/api/java/nio/ByteBuffer.html#put(java.nio.ByteBuffer) The issue is in a call to .get() in aMethodThatReturnsAFilledByteBuffer() – Babak Naffas May 31 '12 at 22:48

2 Answers2

2

Here how it works:

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

Using bytebuffer limit() here, since that's the point where the byteBuffers is filled to. Using capacity() should also work, but can allocate more bytes, than you strictly need.

For limit and capacity I looked see this post: What is the difference between limit and capacity in ByteBuffer?

Frischling
  • 2,100
  • 14
  • 34
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.

user207421
  • 305,947
  • 44
  • 307
  • 483