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() 操作,否則將產生異常。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM