bennyl
bennyl

Reputation: 2956

Java ByteBuffer "put" method - preventing buffer overflow

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?

Upvotes: 0

Views: 3292

Answers (1)

unwind
unwind

Reputation: 400109

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.

Upvotes: 5

Related Questions