首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileInputStream抛出NullPointerException

FileInputStream抛出NullPointerException
EN

Stack Overflow用户
提问于 2010-04-16 05:22:20
回答 3查看 6.5K关注 0票数 0

我得到了nullpointerexception,不知道到底是什么原因造成的。我从java文档中读到fileinputstream只抛出securityexception,所以我不明白为什么会弹出这个异常。这是我的代码片段。

代码语言:javascript
复制
private Properties prop = new Properties();
private String settings_file_name = "settings.properties";
private String settings_dir = "\\.autograder\\";

public Properties get_settings() {
    String path = this.get_settings_directory();
    System.out.println(path + this.settings_dir + this.settings_file_name);
    if (this.settings_exist(path)) {
        try {
            FileInputStream in = new FileInputStream(path + this.settings_dir + this.settings_file_name);
            this.prop.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        this.create_settings_file(path);
        try{
            this.prop.load(new FileInputStream(path + this.settings_dir + this.settings_file_name));
        }catch (IOException ex){
            //ex.printStackTrace();
        }
    }
    return this.prop;
}

private String get_settings_directory() {
    String user_home = System.getProperty("user.home");
    if (user_home == null) {
        throw new IllegalStateException("user.home==null");
    }

    return user_home;
}

下面是我的堆栈跟踪:

代码语言:javascript
复制
C:\Users\mohamed\.autograder\settings.properties
Exception in thread "main" java.lang.NullPointerException
        at autograder.Settings.get_settings(Settings.java:41)
        at autograder.Application.start(Application.java:20)
        at autograder.Main.main(Main.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Line 41 is: this.prop.load(in);
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-04-16 05:28:04

如果第41行是this.prop.load(in);,则看起来好像是this.prop == null

在要验证的行上添加断点。

尝试调用空实例上的方法会导致NullPointerException

票数 1
EN

Stack Overflow用户

发布于 2010-04-16 05:31:29

当变量prop在第41行执行时,它是否为空?试着调试你的程序来检查这一点。例如,添加

代码语言:javascript
复制
if(prop == null)
    System.out.println("prop is null");

此外,NullPointerException是一个未经检查的异常,因此没有在Javadoc中记录。

票数 1
EN

Stack Overflow用户

发布于 2010-04-16 06:10:53

我认为其他评论者在解释你的问题上做得很好。

以下是几点建议:

  1. 我注意到你捕捉到了某些异常,但并没有抛出它们。如果不抛出异常,那么捕获them.
  2. Secondly,就没有意义了。在对对象执行任何操作之前,应该始终检查对象是否为null。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2649073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档