java 尝试读取文件时出现NullPointerException,与之前的代码完全相同[重复]

ncecgwcz  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(129)
    • 此问题在此处已有答案**:

What is a NullPointerException, and how do I fix it?(12个答案)
2天前关闭。
我想运行我两年前写的一个Java程序。它需要两个文件作为命令行参数并读取它们。这个程序以前工作得很好,因为它是一个学校项目,它经历了许多测试,以确保一切正常工作。我下载了我提交的项目,以确保我有相同的版本。这个版本唯一缺少的是要读取的文件,因为我们被要求不要包含它们,而是使用一个路径,这样它们就不会意外地被版本控制跟踪。我将这些文件添加到了主java文件所在的目录中。当我运行程序时,我得到:

Welcome to "Name of school project"
Exception in thread "main" java.lang.NullPointerException
    at practice.collection.Collection.download(Collection.java:100)
    at practice.UI.UI.mainLoop(UI.java:63)
    at mainFile.main(mainFile.java:60)

以下是Collection中的download方法:

public void download(String fileName) {
        Scanner fileReader = null;
        try {
            File file = new File(fileName);
            fileReader = new Scanner(file);
            while (fileReader.hasNextLine()) {
               ***reads lines and does some sorting***
            }
            fileReader.close();
        }
        catch (FileNotFoundException | NumberFormatException e) {
            fileReader.close(); ***this is line 100***
            System.out.println("Missing file!");
            System.out.println("Program terminated.");
            System.exit(0);
        }
    }

我还确保要下载的文件与以前相同,它们不是空的,并且以正确的拼写和正确的顺序调用。java mainFile first_file.txt second_file.txt。为什么程序没有像以前那样找到文件?
我确实 checkout 了What is a NullPointerException, and how do I fix it?,但没有回答我的问题。我认为我得到异常是因为我的程序找不到文件,因此引用了一个空值的文件对象。我试图找出为什么找不到和读取文件。我认为我应该能够修复这个问题,而不接触代码。无论文件是否包含在内,程序的行为都是一样的。

nhaq1z21

nhaq1z211#

用于解决根本问题的建议更改:

public void download(String fileName) {
    System.out.println("fileName=" + fileName + "...");
    System.out.println("current directory=" + System.getProperty("user.dir"));
    Scanner fileReader = null;
    try {
        File file = new File(fileName);
        fileReader = new Scanner(file);
        while (fileReader.hasNextLine()) {
           ***reads lines and does some sorting***
        }
        fileReader.close();
    }
    catch (FileNotFoundException | NumberFormatException e) {
        System.out.println(e);  // Better to print the entire exception
        //System.out.println("Missing file!"); // Q: What about NumberFormatException?
        System.out.println("Program terminated.");
        System.exit(0);
    }
    finally {
       // This assumes your app won't be using the scanner again
       if (fileReader != null)
           fileReader.close(); 
    }
}

相关问题