2016-04-19 39 views
-2

The following is the code:为什么它给我BufferUnderflowException

byte[] topo1={2,1,1,6,6}; 
byte[] topo2={2,1,1,2,2}; 
byte[] topo3={2,5,5,4,4}; 
byte[] topo4={2,3,3,5,5}; 
byte[] topo5={2,4,4,3,3}; 
byte[][] topology = {topo1,topo2,topo3,topo4,topo5}; 
    writeToLog(String.format("%s receives INIT from nse", routerName)); 
writeToLog(" "); 
parseCircuitDB(topology[routerId-1]); 

This the parseCircuitDB method where it shows the error:

private void parseCircuitDB(byte[] string) throws Exception { 
ByteBuffer buffer = ByteBuffer.wrap(string); 
buffer.order(ByteOrder.LITTLE_ENDIAN); 
//gettign the number of neighbor links 
nbrLink = buffer.getInt(); 
System.out.println(nbrLink); 
logMsg = String.format("%d neighbor links exist", nbrLink); 
writeToLog(logMsg); 
for(int i = 1; i <= nbrLink; i++) { 
    //link id as integer 
    int l = buffer.getInt(); 
    System.out.println(l); 
    //link cost as integer 
    int c = buffer.getInt(); 
    link_cost a = new link_cost(l, c); 
    topo_db[routerId].linkCost.put(l, a); 
} 
} 

I get the error BufferUnderflowException. I tried checking the loops but i dont see any problem there.

+0

当相对获取操作达到源缓冲区的限制时,将引发BufferUnderdlowException。你的堆栈跟踪说什么?你可以分享吗? – Krease

+0

异常在线程 “主” java.nio.BufferUnderflowException \t在java.nio.Buffer.nextGetIndex(Buffer.java:506) \t在java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:361) \t在路由器.parseCircuitDB(router.java:218) \t at router.ospf(router.java:140) \t at router。 (router.java:70) \t at router.main(router.java:483) –

回答

2

输入参数string(为一个byte[]非常坏的名称)是5个字节,例如数组02 01 01 06 06(十六进制)。

然后,您使用LITTLE_ENDIAN字节顺序将其包装在ByteBuffer中。

当您然后调用getInt()时,它将消耗4个字节。引述的Javadoc:

Reads the next four bytes at this buffer's current position, composing them into an int value according to the current byte order, and then increments the position by four.

这当然是因为int是一个32位整数,需要用于存储4个8位字节。

因此,将读出的字节02 01 01 06,这在little endian顺序意味着06010102(十六进制),这是100729090(十进制)。 你的println(nbrLink)应该已经告诉过你了。

然后进入循环并再次调用getInt(),试图再读取4个字节,但只剩下1个字节,所以它会抛出BufferUnderflowException

相关问题