InputStream.read() 阻塞(干扰)执行



我一直在编写基本的位级加密代码,我很确定算法是正确的。但我无法测试它。当我运行代码时,第一个循环(使用System.in.read()(会卡住代码。当我通过终端发送EOF信号时,代码不再继续 - 我已经检查了下一行的一些原始print语句。

据我了解,发送EOF应该read()返回-1,退出循环。

我错过了什么?

谢谢。

public class BitLevel {
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream(args[0]);
FileOutputStream output = new FileOutputStream(args[1]);
ArrayList<Integer> key = new ArrayList<Integer>();
int i = 0;
System.out.print("Enter key: ");
System.out.flush();
int c = System.in.read();
while (c != -1) {
key.add((Integer) c);
c = System.in.read();
}
c = input.read();
while (c != -1) {
output.write(c ^ key.get(i).intValue());
output.flush();
i++;
i = i % key.size();
}
}

}

循环永远不会结束,因为"c"不会在其中更改。我想你的意思是也调用循环内的c = input.read();,在它的末尾。

另外,顺便说一句,您应该在完成流后关闭它们。

System.in.read()的调用正好读取一个字节。您可能想使用该Scanner但要解决您的问题,请查看此内容

int c = System.in.read();
while (c != -1) {
key.add((Integer) c);
System.in.read();
}

您读取c一次,并且永远不会通过读取另一个循环在while循环中更改它。将其更改为

int c = System.in.read();
while (c != -1) {
key.add((Integer) c);
c = System.in.read();
}

确实返回了 -1,但您忘记存储返回值以便对其进行测试。

最新更新