尝试使用Scanner从文件中读取int时出现NullPointerException

时间:2014-05-23 13:24:44

标签: java nullpointerexception java.util.scanner

我正在尝试从文件中读取信息。文件中的第一件事是整数,但是当我尝试读取它时,我得到一个NullPointerException。我也尝试将文件中的第一个东西作为字符串读取,然后我又得到了一个N​​ullPointerException。然后我在连接文件时添加了catch语句中的print语句。当我运行代码时,将评估该print语句。我的问题的根源是什么?感谢。

private boolean collectSystem(String loc) {
    Scanner fileIn = null;
    try {
        fileIn = new Scanner(new File(loc));
    } catch (FileNotFoundException e) {
        System.out.println("File not found, IntakeSystem");
    }

    // Determine number of equations
    try {
        n = fileIn.nextInt();
    } catch (InputMismatchException e) {
        return false;
    }

    // Collect the text in the file as a string
    String info = "";
    while (fileIn.hasNextLine()) {
        info = info + fileIn.nextLine();
    }

    fileIn.close();

    //Separate equations in file
    String[] eqns = new String[n];
    int start = 0;
    int end = info.indexOf(";");
    for (int i = 0; i < n; i++) {
        if(end == -1) return false;
        String nextLine = info.substring(start, end);
        eqns[i] = nextLine;
        start = end + 1;
        end = info.indexOf(";", start);
    }

    for (int i = 0; i < n; i++) {
        System.out.println(eqns[n]);
    }

    return true;
}

1 个答案:

答案 0 :(得分:0)

从评论中发现的是,您传递的路径指向的文件不存在,请确保您实际上是先传入有效的文件路径。

通过调试更轻松的方法:

使用System.out.println("File not found, IntakeSystem");throw new IllegalArguementException(e)替换第一个catch块中的return false;,否则您的文件对象仍将为null,如果String loc参数执行,则执行将继续不指向现有文件;通过OP评论是你的问题。