2017-08-15 83 views
-1

我一直在编写基本的位级加密代码,并且我非常确定该算法是正确的..但我无法测试它。当我运行代码时,第一个循环(使用System.in.read())堵塞代码。当我通过终端发送EOF信号时,代码不会进一步发展 - 我在下一行检查了一些原始语句printInputStream.read()阻止(干扰)执行

据我所知,发送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(); 
    } 
} 

}

+0

你可能应该用标准的方式阅读,用'Scanner'等。 – Kayaman

+0

谢谢,Kayaman。我确实错过了“c =”奇怪的是,虽然我修正了这个错误后,错误仍然存​​在。 –

+0

为什么你甚至试图读这种方式?这只是错误的。你会发现从任何基本教程阅读输入的一个体面的例子。 – Kayaman

回答

0

循环将永远不会结束,因为 “C” 没有得到它的内部变化。我想你也打算在循环内呼叫c = input.read();

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

0

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(); 
    } 
0

返回-1,但你忘了存储返回值,所以你可以对它进行测试。