【问题标题】:How to access file within jar file?如何访问jar文件中的文件?
【发布时间】:2016-05-07 19:37:24
【问题描述】:

我的应用程序的类路径中有属性文件。在为此应用程序创建 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 上运行它,错误可能来自这里

【问题讨论】:

标签: java jar


【解决方案1】:

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

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

对这些:

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

让我的代码工作

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 2011-07-07
    • 2011-06-30
    • 2013-07-20
    • 2023-04-10
    • 2012-01-05
    • 2011-01-24
    • 2015-10-07
    相关资源
    最近更新 更多