【问题标题】:Trying to read a resource file from within a jar尝试从 jar 中读取资源文件
【发布时间】:2014-02-03 04:12:35
【问题描述】:

我已经阅读了关于这个主题的每一个问题和答案,并且我尝试了许多建议的解决方案,但都没有奏效,目前我正在尝试使用 URL 资源方法,但 url 总是返回 null。这是我当前的伪设置:

/src/java/pkg/name/is/long/meatpackage/MyClassFile.java

/src/java/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt

@SuppressWarnings("rawtypes")
Class thisClass = Class.forName("pkg.name.is.long.meatpackage.MyClassFile");
ClassLoader cLoader = thisClass.getClassLoader();
//note, I have tried a plethora of variations to the path for the file, this is just one example
URL url = cLoader.getResource("pkg/name/is/long/meatpackage/myresources/myresourcefile.txt");
System.out.println("Found the file!!: " + url);

说真的,在你的 jar 中包含一个文本文件并在运行时访问它不是很难吗?

当我列出 jar 时,它显示该文件位于 pkg/name/is/log/meatpackage/myresources/myresourcefile.txt 中。

我尝试过的另一种方法是:

//along with multiple path combinations for the file the InputStream is always null.    
//multiple paths include but are not limited to:
// "pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/pkg/name/is/long/meatpackage/myresources/myresourcefile.txt"
// "/myresources/myresourcefile.txt"
// "/myresourcefile.txt"
// "myresourcefile.txt"
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("myresourcefile.txt"); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

【问题讨论】:

    标签: java url io classloader getresource


    【解决方案1】:

    您可以使用 getClass().getResourceAsStream() 或 MyClassFile.getResourceAsStream() 简化此操作 - 您无需直接与类加载器对话。

    请注意,资源名称是斜线分隔的,如果指定 / 则它来自 JAR 的根目录或类路径的基础,否则它隐含来自与该类相同的包目录。

    例如:

    包 com.example; 公共类 Foo { 静止的 { Foo.class.getResourceAsStream("bar.txt"); // 寻找 /com/example/bar.txt Foo.class.getResourceAsStream("/bar.txt"); // 寻找 /bar.txt } }

    如果您在 Eclipse 中进行开发,请注意 getResourceAsStream 仅查看编译后的输出目录(即 bin 中的任何内容)。因此,如果您的资源在外面,请将其复制到 src 目录中(以便在构建时将其复制到 bin 目录中),它应该可以正确找到它。

    【讨论】:

    • 那么,调用 this 的方法是否需要是静态的?我在发布之前尝试过这个,因为它是关于类似问题的建议之一,但只是为了确保我在几分钟前再次尝试过。 getResourceAsStream 的任何方法都不会返回非空 InputStream。同样,当我列出 jar 的内容时,文件就在那里,并且我尝试将文件放在您能想到的几乎每个位置。虽然只适合将它放在与类相同的包中的资源目录中,但我尝试将它向上移动到目录结构中,但没有任何效果。
    • Static 没有任何区别。我将方法更改为 static 并使用 MyClassFile.class.getResourceAsStream 无济于事。我准备放弃了..
    • 不,它不需要是静态的。验证您的文件是否在编译后的输出目录中,如果要放入完全限定的包,请确保文件引用以 / 开头。
    • 我验证了该文件在已编译的 jar 中,并且我尝试了所有可以想象的路径组合。我还尝试将文件移动到项目中的各个位置。我终于放弃了,只是将文件的内容放在一个类中.. 似乎是一件愚蠢的事情,但事实就是如此,并且 sprint 截止日期正在迅速逼近..
    猜你喜欢
    • 2021-11-21
    相关资源
    最近更新 更多