我编写了一个Java方法,通过串口向远程设备发送指令,并获取已知数量的字节作为答案。代码使用librxtx-java库在RaspberryPi上运行。验证远程设备发送预期长度的答案。IndexOutOfBoundsException从流中读取时
下面的代码是此方法的最后一部分,RaspberryPi等待答案的所有字节达到给定时间“t_max”。
该代码在System.arraycopy
期间会引发IndexOutOfBoundsException。如果我通过try ... catch包装arraycopy指令并在catch处打印指针变量,确实存在索引溢出。
但是,如果我取消注释打印出指针值的行,则不会再有异常。即使用System.out.println("X");
代替这条线,例外情况也不例外,但System.out.print("X");
则不例外。
我试图将变量更改为不稳定但没有更多的运气。如何才能打印出终端更改变量的值?
long t0 = System.currentTimeMillis();
long t = t0;
byte[] answer = new byte[answerLength];
byte[] readBuffer = new byte[answerLength];
int numBytes = 0;
int answerPointer = 0;
while (t - t0 < t_max) {
try {
if (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
} catch (Exception e) {
}
if (numBytes > 0) {
// System.out.println("answerPointer="+answerPointer);
System.arraycopy(readBuffer, 0, answer, answerPointer, numBytes);
answerPointer = answerPointer + numBytes;
}
if (answerPointer == answerLength) {
return (answer);
}
t = System.currentTimeMillis();
}
方面评论:不要使用'available()'来确定是否有剩余的字节需要读取。相反,只要'read'返回'-1'就停止。另外,请在您的问题中包含您的堆栈跟踪,因为它可能对我们有帮助。 –
这里有几个问题:'Exception'的空接收是坏的,确实非常糟糕。很多奇怪的问题可能会在这里被吞噬,这会让你的代码后来表现得很糟糕。另一件事是你通过尽可能快地循环并检查可用字节来阅读的方式。 – Matthias
在你的while(...){重新初始化你的numBytes为0(并且捕获你的异常! – Tyco