我想要的是通过从控制台通过从BufferedReader读取命令行键入Ctrl z来访问EOF.以下代码这样做.但是问题是,它在达到EOF后发出一个NullPointerException.有没有办法跳过这个例外?或者更确切地说,从控制台读取BufferedReader的方式来达到EOF的正确方法是什么?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class EOF {
public static void main(String args[]) {
String s = "";
String EOF = "^z";
BufferedReader read = new BufferedReader(new InputStreamReader(system.in));
try {
while (!s.equals(EOF)) {
s = read.readLine();
}
} catch (IOException e) {}
}
}
解决方法
Or more precisely,what is the proper way of reaching EOF with bufferedReader reading from console?
目前你实际上是检测到’^’和’z’的字符,它不像’^’真的是一个控制字符.
你得到的例外实际上是一个提示,你应该如何处理这个.从BufferedReader.readLine的文档:
Returns:
A String containing the contents of the line,not including any line-termination characters,or null if the end of the stream has been reached
所以基本上你应该循环直到readLine返回null.
String line;
while((line = read.readLine()) != null)
{
// Do something with line
}