Java 为什么它会给我一个异常

Java 为什么它会给我一个异常,java,parsing,Java,Parsing,代码如下: 这是parseCircuitDB方法,其中显示错误: private void parseCircuitDB(字节[]字符串)引发异常{ ByteBuffer缓冲区=ByteBuffer.wrap(字符串); buffer.order(ByteOrder.LITTLE_ENDIAN); //获取邻居链接的数量 nbrLink=buffer.getInt(); System.out.println(nbrLink); logMsg=String.format(“%d个相邻链接存在”,n

代码如下:

这是parseCircuitDB方法,其中显示错误:

private void parseCircuitDB(字节[]字符串)引发异常{
ByteBuffer缓冲区=ByteBuffer.wrap(字符串);
buffer.order(ByteOrder.LITTLE_ENDIAN);
//获取邻居链接的数量
nbrLink=buffer.getInt();
System.out.println(nbrLink);
logMsg=String.format(“%d个相邻链接存在”,nbrLink);
写日志(logMsg);

对于(int i=1;i输入参数
string
(对于
字节[]
,名称非常糟糕)是一个5字节的数组,例如
02 01 01 06
(十六进制)

然后使用字节顺序将其包装

然后调用时,它将消耗4个字节。引用javadoc:

读取该缓冲区当前位置的下一个四个字节,根据当前字节顺序将它们组合成一个int值,然后将该位置递增四

这当然是因为
int
是32位整数,需要四个8位字节来存储

这将读取字节
02 01 01 06
,按顺序表示
06010102
(十六进制),即
100729090
(十进制)。您的
printlin(nbrLink)
应该已经告诉您了


然后它进入循环并调用
getInt()
再次尝试读取另外4个字节,但只剩下1个字节,因此当相对get操作达到源缓冲区的限制时,它会抛出
BufferUnderflowException

BufferUnderflowException。堆栈跟踪显示了什么?能否共享它?线程“main”中的异常java.nio.BufferUnderflowException位于java.nio.Buffer.nextGetIndex(Buffer.java:506)位于java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:361)位于router.parseCircuitDB(router.java:218)位于router.ospf(router.java:140)位于router.main(router.java:483)
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]);
 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);
}   
}