简体   繁体   中英

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");

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, eg by using a StreamClassLoader to load the inner jar

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM