java.nio.BufferUnderflowException

 java.nio.BufferUnderflowException:

完整的错误信息:

Exception in thread "main" java.nio.BufferUnderflowException  
    at java.nio.HeapByteBuffer.get(HeapByteBuffer.java:151)  
    at com.weixiao.network.GatewayInstanceTest.main(GatewayInstanceTest.java:169)  

例如如下代码:

ByteBuffer params = ByteBuffer.allocate(2);//   这里只分配了2个字节,下面的params.get(tmp);却get了3个字节的数据。所以导致 java.nio.BufferUnderflowException 异常  
        params.order(ByteOrder.LITTLE_ENDIAN);   
        byte[] tmp = new byte[3];  
    params.get(tmp);  

错误原因:读取超出了原有的长度。

解决方法:

添加读取长度与 ByteBuffer 中可读取的长度的判断,例如:

while (writeBuffer.remaining() > 0) {  
    byte b = writeBuffer.get();  
} 

注意:你每次只读取一个字节,那就判断大于0就好了,如果不是一个记得修改条件哦!

总结:

当 ByteBuffer.remaining()  小于要读取或写入的长度时,再执行读取或写入操作都会产生异常;

读取则产生 java.nio.BufferUnderflowException 异常,

写入则产生 java.nio.BufferOverflowException 异常。

当 ByteBuffer.remaining()  等于 0 时,不能再执行读取或写入操作,需要执行:clear() 操作,否则将产生异常。

 

原文地址:https://www.cnblogs.com/5icuke/p/8482422.html