java - 无法从 jar 加载属性

标签 java properties path nullpointerexception embedded-resource

我有一个小应用程序,我测试并打包到 jar 并尝试运行它,但出现错误。

这是我的项目结构:

src
  -kie.template
  ----- ServerMain.java   ==> Class with main
  -kie.template.util
  ---- PropUtils.java
  ---- server.properties
target
  -kietemplate.jar
  ---- lib

在main方法中,PropUtils类读取属性。

public class PropUtils {

    private static final String PROPERTIES = "server.properties";

    public static Properties load() {
    Properties properties = new Properties();
            InputStream is = null;
            try {
                properties.load(PropUtils.class.getResourceAsStream(PROPERTIES));

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is!=null) try{is.close();}catch(IOException e){}
            }

            return properties;
        }
     }
}

当我直接运行 ServerMain 类时,它工作正常。但是当我打包成jar并运行后,它显示错误:

java -cp lib -jar kietemplate.jar

Caused by: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:418)
    at java.util.Properties.load0(Properties.java:337)
    at java.util.Properties.load(Properties.java:325)
    at au.org.jeenee.kie.template.util.PropUtils.load(PropUtils.java:26)

当我查看 jar 文件时,属性文件位于目录中。 jar tf kietemplate.jar

任何帮助将非常感激。

编辑: 我更改了读取属性的逻辑:

Properties properties = new Properties();
InputStream is = null;
try {
    File file = new File("server.properties");
    is = new FileInputStream(file);
    properties.load(new InputStreamReader(is));
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (is!=null) try{is.close();}catch(IOException e){}
}

它需要 jar 文件的父目录中的属性文件。

最佳答案

您的代码在我的计算机上运行良好,无论是来自 JAR 还是文件系统。

导致该行为的一个可能原因是文件系统不区分大小写,但 jar 文件区分大小写。但仅从源代码我们确实无法判断。

关于java - 无法从 jar 加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519343/

相关文章:

java - 为什么 PathMatcher 不匹配路径?

java - (OOP/Java) 我应该如何处理这种子类-父类(super class)关系?

java - 比较两个字符串数组而不通过每个元素进行索引的最佳方法是什么?

java - 通过网络将参数/参数传递给 jnlp。有哪些选择?

c# - 将 IEnumerable 转换为属性列表

python - 使用 Anaconda python 代替默认的 mac python

java - 当我复制两个空路径时会发生什么并且为什么它不抛出异常?

java - 删除 Gradle 默认源集

java - 如果 yml 文件不存在,则在 mysql 中创建数据库时出错

java - 重构帮助...基于属性的对象或大量成员字段?