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