【问题标题】:Cannot load properties from jar无法从 jar 加载属性
【发布时间】:2013-07-08 04:48:24
【问题描述】:

我有一个小应用程序,我测试并打包到 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 中的server.properties 是什么路径?执行jar -tvf kietemplate.jar 并将输出添加为编辑。
  • 文件中的一些类名。 channel.s911=mypackge.server.ClientInitializer

标签: java properties path nullpointerexception embedded-resource


【解决方案1】:

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

导致该行为的一个可能原因是文件系统不区分大小写,但 jar 文件区分大小写。但是我们真的不能仅从源代码中分辨出来。

【讨论】:

  • 谢谢。我正在 MacOSX 上进行测试,我将对其进行更多调查。
  • 我使用 File 类稍微改变了读取属性的逻辑。无论如何,现在它可以工作了。
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 2015-08-20
  • 2021-12-29
  • 2014-12-30
  • 2014-11-17
  • 2013-01-11
  • 1970-01-01
相关资源
最近更新 更多