如何在jar文件中访问文件?

时间:2016-05-07 19:37:24

标签: java jar

我的应用程序的类路径中有属性文件。在为此应用程序创建jar文件之前没有问题,但是当我创建jar文件并使用java -jar命令运行它时,它返回null pointer exception。这是我加载属性的代码:

private Properties loadProperties() {
    Properties prop = new Properties();
    InputStream input = null;

    try {
        input = this.getClass().getResourceAsStream("./auth");
        prop.load(input);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return prop;
}

我可以在jar中访问属性文件,但是不可能吗?

以下是我得到的例外情况:

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.kadir.MyApp.loadProperties(MyApp.java:109)
    at com.kadir.MyApp.<init>(MyApp.java:62)
    at com.kadir.MyApp.main(MyApp.java:48)

和第108和109行是这些:

    input =this.getClass().getClassLoader().getResourceAsStream("auth");
    prop.load(input);

还有一点需要注意:我正在Windows上开发我的应用程序,但是在Linux上运行它,错误可能来自此

1 个答案:

答案 0 :(得分:0)

我不知道为什么它不起作用的确切原因,但改变这两行

input = this.getClass().getResourceAsStream("auth");
prop.load(input);

到这些:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
input = classloader.getResourceAsStream("auth");
prop.load(input);

让我的代码正常工作

相关问题