![](/img/trans.png)
[英]IndexOutOfBoundsException when reading from a ZipInputStream Java
[英]IndexOutOfBoundsException when reading from stream
我编写了Java方法,以通过串行端口将指令发送到远程设备,并获得已知的字节数作为答案。 该代码使用librxtx-java库在RaspberryPi上运行。 已验证远程设备已发送预期长度的答案。
下面的代码是该方法的最后一部分,其中RaspberryPi在给定时间“ t_max”内等待答案的所有字节。
代码本身在System.arraycopy
期间引发IndexOutOfBoundsException。 如果我通过try ... catch包装arraycopy指令并在catch处打印出指针变量,则确实存在索引溢出。
但是,如果取消注释打印出指针值的行,就不会再有例外了。 甚至用System.out.println("X");
替换此行System.out.println("X");
使异常消失,但System.out.print("X");
则不这样做System.out.print("X");
例如。
我尝试将变量更改为volatile,但是没有运气了。 如何在终端打印输出以更改变量的值?
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();
}
您是否尝试验证输出流和输入流是否以任何方式链接? 可能是输入流正在从输出流中读取,并且'\\ n'(换行)被用作流字符的结尾。 您可以尝试打印到围绕字节数组输出流而不是标准输出的打印流包装中,并查看执行ps.println(“ X”)是否导致异常吗? 如果确实引起异常,则可能将标准输出流和输入流链接在一起,这就是为什么执行System.out.println(“ X”)会使异常消失的原因。
另外,在线程上下文中使用volatile关键字。 它在单线程环境中不会有任何影响。
如果代码inputStream.available()
在while (t - t0 < t_max)
变量numBytes
和readBuffer
第二次迭代中引发异常, while (t - t0 < t_max)
使用旧值进行初始化。 尝试将while (t - t0 < t_max)
所有代码包装在try {} catch {}
,不要隐藏异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.