java 访问 JAR 资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2639943/
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
Accessing JAR resources
提问by Pablo Fernandez
I have a jarfile with resources (mainly configuration for caches, logging, etc) that I want to distribute.
我有一个jar包含要分发的资源(主要是缓存、日志记录等配置)的文件。
I'm having a problem with the relative paths for those resources, so I did what I've found in another stackoverflow question, which said that this was a valid way:
我对这些资源的相对路径有问题,所以我做了我在另一个 stackoverflow 问题中发现的问题,它说这是一种有效的方法:
ClassInTheSamePackageOfTheResource.class.getResourceAsStream('resource.xml');
Sadly this does not work.
可悲的是,这不起作用。
Any ideas? Thanks!
有任何想法吗?谢谢!
PS: Obviously I cannot use absolute paths, and I'd like to avoid environment variables if possible
PS:显然我不能使用绝对路径,如果可能的话我想避免环境变量
回答by Marcus Adams
Make sure that your resource folder is listed as a source folder in your project settings. Also, make sure that the resource folder is set to export when you build your jar.
确保您的资源文件夹在您的项目设置中列为源文件夹。此外,请确保在构建 jar 时将资源文件夹设置为导出。
You can add a .zip extension to your jar file then open it up to ensure that your resources are included and at the expected location.
您可以向 jar 文件添加 .zip 扩展名,然后将其打开以确保包含您的资源并位于预期位置。
I always use absolute paths like this:
我总是使用这样的绝对路径:
InputStream input = this.getClass().getResourceAsStream("/image.gif");
When you use absolute paths, "/" is the root folder in the jar file, not the root folder of the host machine.
使用绝对路径时,“/”是jar文件中的根文件夹,不是宿主机的根文件夹。
回答by trashgod
I always have to puzzle through getResourceAsStreamto make this work. If "resource.xml" is in org/pablo/opus, I thinkyou want this:
我总是不得不费解getResourceAsStream才能完成这项工作。如果“resource.xml”在org/pablo/opus,我想你想要这个:
Name.class.getResourceAsStream("org.pablo.opus.resource.xml");
回答by Seffi
where the resource.xml found? If in the root of the source tree, try to prefix it with /.
在哪里找到resource.xml?如果在源代码树的根目录中,请尝试使用 / 作为前缀。
回答by Jason Nichols
I usually store files and other resources and then retrieve them as URLs:
我通常存储文件和其他资源,然后将它们作为 URL 检索:
URL url = MyClass.class.getResource("/design/someResource.png");
Within a static context, or otherwise:
在静态上下文中,或以其他方式:
URL url = getClass().getResource("/design/someResource.png");
From an instance.
从一个实例。
The above snippets assume that design is a top level folder within the jar. In general, if the path begins with a "/" it assumes an absolute path, otherwise it's relative from the class location.
上面的代码片段假设 design 是 jar 中的顶级文件夹。通常,如果路径以“/”开头,则它假定为绝对路径,否则它是相对于类位置的。

