0

我想通过以下方式使用 java nio ByteBuffer 的 put 方法:

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

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

put 方法会抛出缓冲区溢出异常,所以我修复它的方法是:

 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);
 }

我的问题是 - 有没有更好的方法来做到这一点,或者至少有一种有效的方法来做我想做的事?

4

1 回答 1

5

hasRemaining()好吧,您实际上可以调用而不是使用 booleanremaining()来确定剩余的字节数。

然后,您可以使用一个小的固定大小的中间字节数组以及基于数组的get()put()方法来传输“块”字节,根据剩余空间量调整放入中间缓冲区的字节数。

于 2012-05-16T11:34:53.947 回答