【问题标题】:Fileinputstream NullPointerException Java [duplicate]Fileinputstream NullPointerException Java [重复]
【发布时间】:2019-06-11 17:49:38
【问题描述】:

我在 StackOverflow 上搜索了此错误,但发现任何主题都可以解决我的问题。我有这段代码可以打开一个 .txt 文件并初始化对象变量,然后出现这个错误。

public void lerDoArquivo() {
    try {
        FileReader ler = new FileReader("Menu_de_itens.txt");
        BufferedReader reader = new BufferedReader(ler);
        String linha;

        while ((linha = reader.readLine()) != null) {
            processaEntrada(linha);
        }

        reader.close();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }  
}

这是我的轨迹:

Exception in thread "main" java.lang.NullPointerException
    at java.io.FileInputStream.<init>(FileInputStream.java:130)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at ItemMenuDAOTxt.lerDoArquivo(ItemMenuDAOTxt.java:22)
    at ItemMenuDAO.<init>(ItemMenuDAO.java:16)
    at ItemMenuDAOTxt.<init>(ItemMenuDAOTxt.java:14)
    at ControleDeMenu.<init>(ControleDeMenu.java:21)
    at FastFoodOO.main(FastFoodOO.java:11)

【问题讨论】:

  • 找不到文件:“./resources/Menu_de_itens.txt”
  • 找不到文件。在运行时阅读类路径并使用 getClass().getResourcegetClassLoader().getResource 或其流变体
  • new FileReader 只会在你传入null 值时抛出NullPointerException。如果是因为文件不存在,正如其他人所建议的那样,你会得到FileNotFoundException
  • 我同意@Andreas。有什么你没有在这里发布的吗?
  • 如前所述,除非你传入一个空参数值,否则你不应该得到那个异常。但是,如果您不同意,为什么不拿起您方便的 IDE 并查看类 FileInputStream 的源代码的第 130 行,看看该行做了什么,以及为什么它会导致 NPE?或者,我的天啊,使用 IDE 的内置调试器单步调试代码,并亲自查看这些值是什么以及发生了什么?

标签: java nullpointerexception fileinputstream


【解决方案1】:

确认您可以读取该文件,很可能找不到该文件。

 assert new File("./resources/Menu_de_itens.txt").canRead();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多