Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a resource from an embedded JAR File

I am trying to load a resource that is contained within an embedded JAR file. The project is actually deployed in JBoss using an EAR file with the following structure:

deploy.ear
|
|-> project.sar
    |
    |-> sub_project.jar
    |   |
    |   |-> settings.xml
    |
    |-> com/path/project/
        |
        |-> main.class

From main.java I'd like to get a InputStream for settings.xml. What is the correct way to do this?

My current understanding that the following code should work, but it is returning null:

this.getClass().getResourceAsStream("settings.xml");

Update

After some trial and error, the following statements work:

getClass().getResourceAsStream("/settings.xml");
getClass().getResourceAsStream("/sub_project.jar/settings.xml");
getClass().getClassLoader().getResourceAsStream("/settings.xml");
getClass().getClassLoader().getResourceAsStream("settings.xml");
getClass().getClassLoader().getResourceAsStream("sub_project.jar/settings.xml");
getClass().getClassLoader().getResourceAsStream("/sub_project.jar/settings.xml");
like image 417
cmcginty Avatar asked Nov 06 '22 00:11

cmcginty


1 Answers

This might be a good resource: http://one-jar.sourceforge.net/version-0.95/

The main idea is that the inner JAR is not loaded by the ClassLoader that loaded the outer JAR automatically, you need to do so manually, e.g. by using a StreamClassLoader to load the inner jar

Only then, from your own ClassLoader you can get that resource using getResourceAsStream(...)

like image 128
Eran Medan Avatar answered Nov 09 '22 11:11

Eran Medan