用Java解析文本文件 - 需要帮助理解NullPointerException

时间:2016-11-12 22:55:12

标签: java nullpointerexception text-files

我对Java很新,我很难理解扫描程序和异常。它在“while(!line.matches(”[\ n \ r] +“))”“中显示NullPointerException。我不确定为什么会这样。我初始化了行变量,我假设如果扫描器的下一行是断行,则while循环应该结束。如果下一行为null,那么整个外部循环应该结束。为什么返回NullPointerException?

public class Readfile {
private static int inputs = 0;

public void main(String filename) throws Exception {
    URL url = getClass().getResource(filename);
    File file = new File(url.getPath());
    parsefile(file);

}

void parsefile(File file) throws Exception {
    ArrayList<String[]> Inputs = new ArrayList<String[]>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = br.readLine();
    while (line != null){
        LinkedList currentinput = new LinkedList();
        if (line.contains("Input")){
            while (! line.matches("[\\n\\r]+")) {
                System.out.println(line);
                line = br.readLine();
            }
        }else{
            line = br.readLine();
        }
    }
}

}

1 个答案:

答案 0 :(得分:4)

您的内部循环也会调用br.readLine(),因此您需要检查null。变化

while (! line.matches("[\\n\\r]+")) {

类似

while (line != null && ! line.matches("[\\n\\r]+")) {

while (! line.matches("[\\n\\r]+")) {
    System.out.println(line);
    line = br.readLine();
    if (line == null) {
        break;
    }
}