Thursday, April 7, 2011

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 must get one file name (instead of a dir) and I'll use it by this way:

System.setProperty("javax.net.ssl.trustStore", fileNameString)
From stackoverflow
  • Construct a URL, you can then load a resource (even in a jar file) using the openStream method.

  • 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.

    Thorbjørn Ravn Andersen : Agree. Whenever you cannot say with 100% certainty that you will deal with physical single files (java web start for one) you should always code with streams.
    Giancarlo : added some info take a look :)

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.