0

I want to use the put method of the java nio ByteBuffer in the following way:

ByteBuffer small = ByteBuffer.allocate(SMALL_AMOUNT_OF_BYTES);
ByteBuffer big = getAllData();

while (big.hasRemaining()){
    small.put(big);
    send(small);
}

the method put will throw buffer overflow exception, so what i does to fix it was:

 ByteBuffer small = ByteBuffer.allocate(SMALL_AMOUNT_OF_BYTES);
 ByteBuffer big = getAllData();

 while (big.hasRemaining()){
     while (small.hasRemaining() && big.hasRemaining()){
         small.put(big.get());
     }

     send(small);
 }

my question is - is there a better way to do so or at least an efficient way to do what i want?

bennyl
  • 2,886
  • 2
  • 29
  • 43

1 Answers1

5

Well, instead of using the boolean hasRemaining(), you can actually call remaining() to figure out exactly how many bytes are remaining.

Then you could use a small fixed-size intermediate byte array together with the array-based get() and put() methods to transfer "chunks" of bytes, adjusting the number of bytes put into the intermediate buffer based on the amount of remaining space.

unwind
  • 391,730
  • 64
  • 469
  • 606