加载包含在 jar 中的资源 [英] Load a resource contained in a jar
问题描述
在我的应用程序中,我以这种方式加载资源:
In my application I load resources in this manner:
WinProcessor.class.getResource("repository").toString();
这给了我:
file:/root/app/repository (and I replace "file:" with empty string)
当我从 IDE 运行我的应用程序时,这工作正常,但是当我运行我的应用程序的 jar 时:
This works fine when I run my application from the IDE, but when I run the jar of my application:
java -jar app.jar
路径变为:
jar:/root/app.jar!/repository
有什么办法可以解决这个问题吗?
is there any way to solve this problem?
我将使用存储库"目录名称来创建它:
I'll use the "repository" dir name in order to create this:
ConfigurationContext ctx = (ConfigurationContext) ConfigurationContextFactory.createConfigurationContextFromFileSystem(repositoryString, null);
以同样的方式,我会得到一个文件名(而不是目录),我会这样使用它:
In the same manner, I'll get one file name (instead of a dir) and I'll use it this way:
System.setProperty("javax.net.ssl.trustStore", fileNameString)
推荐答案
听起来您正在尝试使用 FileInputStream
或类似方法加载资源.不要这样做:不要调用 getResource
,而是调用 getResourceAsStream
并从中读取数据.
It sounds like you're then trying to load the resource using a FileInputStream
or something like that. Don't do that: instead of calling getResource
, call getResourceAsStream
and read the data from that.
(您可以改为从 URL 加载资源,但调用 getResourceAsStream
更方便一些.)
(You could load the resources from the URL instead, but calling getResourceAsStream
is a bit more convenient.)
看到您更新的答案后,似乎其他代码位依赖于文件系统中物理单个文件中的数据.因此,答案首先不是将其捆绑在 jar 文件中.您可以检查它是否在一个单独的文件中,如果不能将其解压缩到一个临时文件中,但这在 IMO 中是非常棘手的.
Having seen your updated answer, it seems other bits of code rely on the data being in a physical single file in the file system. The answer is therefore not to bundle it in a jar file in the first place. You could check whether it's in a separate file, and if not extract it to a temporary file, but that's pretty hacky IMO.
这篇关于加载包含在 jar 中的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!