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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.