加载jar中包含的资源

加载jar中包含的资源

本文介绍了加载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?

我将使用repository目录名来创建:

I'll use the "repository" dir name in order to create this:

ConfigurationContext ctx = (ConfigurationContext) ConfigurationContextFactory.createConfigurationContextFromFileSystem(repositoryString, null);

以同样的方式,我会得到一个文件名(而不是dir)而且我'以这种方式使用它:

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 ,调用并从中读取数据。

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文件中。你可以检查它是否在一个单独的文件中,如果没有将它提取到一个临时文件中,但这是非常hacky的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中包含的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:01