jar 中的类路径资源 [英] Classpath resource within jar

查看:29
本文介绍了jar 中的类路径资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目 A,其中包含一些 java 文件和一个类路径资源 R.txt.在项目中我使用 ClassLoader.getSystemResource("R.txt");检索 R.txt.

I have a project A, which contains some java files and a classpath resource R.txt. Within the project I use ClassLoader.getSystemResource("R.txt"); to retrieve R.txt.

然后我有一个项目 B,其中包含项目 A 的 jar 文件.现在 getSystemResource("R.txt") 不会找到文本文件(是的,它仍然在 jar 文件的根目录中).即使按照其他网站上的建议尝试/R.txt"也不起作用.有任何想法吗?

Then I have a project B which includes project A's jar-file. Now getSystemResource("R.txt") wont find the textfile (and yes, it's still in the root of the jar file). Even trying "/R.txt" as was suggested on some other site didn't work. Any ideas?

推荐答案

使用 getResource 而不是 getSystemResource 来使用特定于给定类加载器而不是系统的资源.例如,尝试以下任一操作:

Use getResource instead of getSystemResource to use a resource specific to a given classloader instead of the system. For example, try any of the following:

URL resource = getClass().getClassLoader().getResource("R.txt");
URL resource = Foo.class.getClassLoader().getResource("R.txt");
URL resource = getClass().getResource("/R.txt");
URL resource = Foo.class.getResource("/R.txt");

在调用 Class.getResource 而不是 ClassLoader.getResource;Class.getResource 是相对于包含类的包,除非你有一个前导斜线,而 ClassLoader.getResource 总是绝对的.

Note the leading slash when calling Class.getResource instead of ClassLoader.getResource; Class.getResource is relative to the package containing the class unless you have a leading slash, whereas ClassLoader.getResource is always absolute.

这篇关于jar 中的类路径资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆