Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

java - Load a resource contained in a jar

In my application I load resources in this manner:

WinProcessor.class.getResource("repository").toString();

and this gives me:

file:/root/app/repository   (and I replace "file:" with empty string)

This works fine when I run my application from the IDE, but when I run the jar of my application:

java -jar app.jar

The path becomes:

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)
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(You could load the resources from the URL instead, but calling getResourceAsStream is a bit more convenient.)

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...