访问 JAR 资源
我有一个 jar
文件,其中包含我想要分发的资源(主要是缓存、日志记录等配置)。
我对这些资源的相对路径有问题,所以我做了我在另一个 stackoverflow 问题中发现的事情,该问题说这是一种有效的方法:
ClassInTheSamePackageOfTheResource.class.getResourceAsStream('resource.xml');
遗憾的是,这不起作用。
有什么想法吗?谢谢!
PS:显然我不能使用绝对 路径,我想避免 环境变量(如果可能)
I have a jar
file with resources (mainly configuration for caches, logging, etc) that I want to distribute.
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:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我通常存储文件和其他资源,然后将它们作为 URL 检索:
在静态上下文中,或者
从实例中检索。
上面的代码片段假设 design 是 jar 中的顶级文件夹。一般来说,如果路径以“/”开头,则假定为绝对路径,否则它是相对于类位置的路径。
I usually store files and other resources and then retrieve them as URLs:
Within a static context, or otherwise:
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.
确保您的资源文件夹在项目设置中列为源文件夹。另外,请确保在构建 jar 时将资源文件夹设置为导出。
您可以向 jar 文件添加 .zip 扩展名,然后将其打开,以确保您的资源包含在内并位于预期位置。
我总是这样使用绝对路径:
当使用绝对路径时,“/”是jar文件中的根文件夹,而不是主机的根文件夹。
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.
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.
I always use absolute paths like this:
When you use absolute paths, "/" is the root folder in the jar file, not the root folder of the host machine.
我总是不得不困惑
getResourceAsStream
来完成这项工作。如果“resource.xml”位于org/pablo/opus
中,我认为您想要这样:I always have to puzzle through
getResourceAsStream
to make this work. If "resource.xml" is inorg/pablo/opus
, I think you want this:在哪里找到resource.xml?如果位于源树的根目录中,请尝试在其前面添加 / 前缀。
where the resource.xml found? If in the root of the source tree, try to prefix it with /.