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

相關文章
相關標籤/搜索