问题描述
我想要的是通过在命令行中输入<$ c $来达到 EOF
,方法是 + c> BufferedReader 从控制台读取。以下代码这样做。但是问题是,在达到 EOF
之后,它会发出 NullPointerException
。有没有办法跳过此异常?或者更确切地说,通过控制台读取 BufferedReader
达到 EOF
的正确方法是什么?
What I wanted is to reach EOF
by typing + from command line with BufferedReader
reading from console. The following code does so. But the problem is, it issues a NullPointerException
after reaching EOF
. Is there a way to skip this exception? Or more precisely, what is the proper way of reaching EOF
with BufferedReader
reading from console?
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) {}
}
}
推荐答案
当前,您实际上正在检测字符'^'和'z',而不是'^'确实是控制字符。
Currently you're actually detecting the characters '^' and 'z' it's not like '^' is really a control character.
实际上,您得到的异常提示应该如何处理。从:
The exception you're getting is actually a hint as to how you should be handling this. From the docs for BufferedReader.readLine:
readLine
返回 null
。
String line;
while((line = read.readLine()) != null)
{
// Do something with line
}
这篇关于文件结尾NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!