【问题标题】:Executable .jar fails to start because of .properties file loading由于 .properties 文件加载,可执行 .jar 无法启动
【发布时间】:2012-06-25 13:34:20
【问题描述】:

我在运行可执行 .jar 文件时遇到问题。我创建了一个包含 .properties 文件的项目。当我从 eclipse 启动它时它工作得很好,但是当我将它导出到可执行的 .jar 文件并尝试运行它时:

java -jar myfile.jar

我得到以下异常:

(无法在此处发布图片) http://imageshack.us/photo/my-images/824/29583616.png/

我检查了 .jar 中的清单文件,其中包含

Class-Path: .

这是加载的属性文件:

properties = new Properties();
    properties.load(new FileInputStream(
            "src/com/resources/treeView.properties"));

知道是什么导致了这个异常吗?

【问题讨论】:

  • 尝试 "properties = new Properties(); properties.load(new FileInputStream( "/com/resources/treeView.properties"));"路径中没有“src”。

标签: java jar executable-jar properties-file


【解决方案1】:

在 Eclipse(以及大多数 IDE)中,当前目录是项目的根目录。这意味着 Class-Path: . 在 Eclipse 中的含义与从命令行运行时不同。这就是你写“src/com/...”的原因。删除“src”:

properties.load(new FileInputStream("com/resources/treeView.properties"));

【讨论】:

    【解决方案2】:

    如果属性文件在 jar 文件中,则不能将其作为文件访问。

    您需要让类加载器将资源作为输入流获取。见Getting the inputstream from a classpath resource (XML file)

    【讨论】:

    • 谢谢!那行得通! properties.load(ClassLoader.class.getResourceAsStream("/com/resources/treeView.properties"));
    【解决方案3】:

    您的属性文件在 JAR 文件中。所以,使用:ClassLoader.getResourceAsStream()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2011-02-05
      相关资源
      最近更新 更多