jar中的classpath资源 [英] Classpath resource within 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中的classpath资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!