java.nio.BufferUnderflowException

 java.nio.BufferUnderflowException:

完整的错误信息:java

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

 

例如以下代码:spa

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

 

错误缘由:读取超出了原有的长度。.net

解决方法:code

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

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

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

总结:

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

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

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

当 ByteBuffer.remaining()  等于 0 时,不能再执行读取或写入操做,须要执行:clear() 操做,不然将产生异常。class

相关文章
相关标签/搜索