Java jar 中的类路径资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1900154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:40:07  来源:igfitidea点击:

Classpath resource within jar

javajarclasspathresources

提问by Johan Sj?berg

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.

我有一个项目 A,其中包含一些 java 文件和一个类路径资源 R.txt。在项目中我使用 ClassLoader.getSystemResource("R.txt"); 检索 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?

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

采纳答案by Jon Skeet

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

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

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");

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

请注意调用时的前导斜杠Class.getResource而不是ClassLoader.getResource; Class.getResource除非您有前导斜杠,否则相对于包含该类的包,而ClassLoader.getResource始终是绝对的。

回答by Michael Borgwardt

Apparently your JAR is not loaded by the system classloader, so getSystemResource()can't work. This should work:

显然你的 JAR 没有被系统类加载器加载,所以getSystemResource()不能工作。这应该有效:

ClassFromProjectA.class.getClassLoader().getResource("R.txt")

IMO more convenient is putting resources inside the same package as the classes that use them, so you can use the shorter

IMO 更方便的是将资源与使用它们的类放在同一个包中,因此您可以使用较短的

ClassFromProjectA.class.getResource("R.txt")

(or, inside that class just getClass().getResource("R.txt"))

(或者,在那个班级里面getClass().getResource("R.txt")

回答by Brian Agnew

Does ClassLoader.getResource()work ? At the moment you're simply specifying that the system classloader is to be used.

ClassLoader.getResource方法,()的工作?目前,您只是指定要使用系统类加载器。