Java ByteBuffer"put"方法 - 防止缓冲区溢出

ben*_*nyl 0 java networking nio bytebuffer

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

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

while (big.hasRemaining()){
    small.put(big);
    send(small);
}
Run Code Online (Sandbox Code Playgroud)

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);
 }
Run Code Online (Sandbox Code Playgroud)

我的问题是 - 有更好的方法这样做,或者至少有效的方式来做我想要的吗?

unw*_*ind 5

好吧,hasRemaining()您可以实际调用remaining()以确切地确定剩余的字节数,而不是使用布尔值.

然后,你可以一起使用小固定大小的中间字节数组与基于阵列的get()put()方法传输的字节的"块",调整投入基于剩余空间的量的中间缓冲器的字节数.