【问题标题】:JAR file not finding embedded resource -- issue with relative path? [duplicate]JAR 文件未找到嵌入式资源——相对路径有问题? [复制]
【发布时间】:2013-07-10 13:40:01
【问题描述】:

我有一个通过这个命令手动创建的 JAR 文件(换行以便于阅读)

jar -cfm app_standalone.jar manifest.txt 
application/client/*.class
application/data/*.class  
application/startup/*.class 
*.txt

清单如下所示:

Main-Class: application.startup.StartFrame

我在/application/ 之外的目录中运行此命令。生成的 JAR 的目录结构如下所示:

[ROOT_DIR_OF_JAR]/type1.txt
[ROOT_DIR_OF_JAR]/type2.txt
[ROOT_DIR_OF_JAR]/type3.txt
[ROOT_DIR_OF_JAR]/application
[ROOT_DIR_OF_JAR]/application/client/example.class
[ROOT_DIR_OF_JAR]/application/data/another.class
[ROOT_DIR_OF_JAR]/application/startup/run_me.class

当我运行 JAR 文件时,它可以正常执行,但如果它与 .txt 文件位于同一目录中,显然是在引用它。指向那些.txt 文件的代码位于/application/client/ 中:

package application.client;
String typeName = "type2";  // could be type1 or type3
InputStream is = modelViewer.modelEnv.openFile(typeName + ".txt");
// ===============================================================
package application.startup;
public InputStream openFile(String name) {
    File f;
    FileInputStream is = null;
    String dir = System.getProperty("user.dir");
    f = new File(dir, name);
    is = new FileInputStream(f);
    return is;
}

我尝试使用/client/ 目录中的.txt“资源”文件创建JAR,但没有成功。正如其他类似问题的答案所建议的那样,我也尝试过更改代码中的路径。我猜这是使用相对路径的某种问题。我该怎么做才能使这些文件在 JAR 中正确引用,以便应用程序可以独立运行?

【问题讨论】:

  • typeName 的值是多少?为了尽快获得更好的帮助,请发帖SSCCE
  • typeName 只是一个字符串,它对应于 .txt 文件名之一 -- type1type2type3。抱歉,我认为这是不言而喻的。
  • “我认为这是不言而喻的。” SSCCE 是“不言而喻的”。你的呢?
  • @RC。 - 这样可行。我以为我已经尝试过了,但事实证明我当时没有正确创建 JAR 文件。 >.
  • 不知道 openFile() 做了什么,很难解释为什么它是对还是错。

标签: java jar embedded-resource


【解决方案1】:

该方法不会从类路径加载文件,而是从文件系统中的当前目录加载文件。这就是问题所在。

要从类路径加载资源,必须使用Class.getResourceAsStream()(或ClassLoader.getResourceAsStream())。

【讨论】:

  • 当我最终查看openFile() 方法的实现时,非常明显——感谢您为我指明了这个方向!
猜你喜欢
  • 2021-02-28
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
相关资源
最近更新 更多