调试时空指针(java.io.File)异常消失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12859514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:31:08  来源:igfitidea点击:

null pointer (java.io.File) exception dissappears while debugging

javadebuggingfile-io

提问by July

I have an application which throws this error (happens only with xlsx-files):

我有一个抛出此错误的应用程序(仅发生在 xlsx 文件中):

java.lang.NullPointerException
at java.io.File.<init>(File.java:222)
at de.mpicbg.tds.core.ExcelLayout.openWorkbook(ExcelLayout.java:75)

The method 'openWorkbook' looks like this:

'openWorkbook' 方法如下所示:

    private void openWorkbook() throws IOException {
    File excelFile = new File(fileName);

    timestamp = excelFile.lastModified();

    // open excel file
    if (fileName.endsWith(".xlsx")) {
        InputStream excelStream = new BufferedInputStream(new FileInputStream(excelFile));
        this.workbook = new XSSFWorkbook((excelStream));

    } else {
        this.workbook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(excelFile)));
    }
}

If I execute everything in debug mode, everything goes smoothly and the error message does not appear. I don't have any explanation for this behaviour nor any idea how to fix it. Can anybody help?

如果我在调试模式下执行所有内容,一切都会顺利进行,并且不会出现错误消息。我对这种行为没有任何解释,也不知道如何解决它。有人可以帮忙吗?

回答by Peter Lawrey

The error message says your fileNameis null

错误消息说你fileNamenull

If you cannot reproduce this when debugging you can add a log message at the start of you method.

如果在调试时无法重现这一点,您可以在方法开始时添加一条日志消息。

System.out.println("The fileName is `" + fileName+"`");

Instead of using a field which may or may not be set, I suggest you use a parameter.

我建议您使用参数,而不是使用可能设置或可能未设置的字段。

private void openWorkbook(String fileName) throws IOException {
    assert fileName != null;