How to load a resource from an embedded JAR File

余生长醉 提交于 2019-12-22 07:43:23

问题


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

回答1:


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(...)



来源:https://stackoverflow.com/questions/5602367/how-to-load-a-resource-from-an-embedded-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!