Find a resource (.txt file) in war file which is deployed standalone or in ear

拥有回忆 提交于 2019-12-13 16:55:57

问题


I have a war file is packaged in ear and deployed. Here is the structure:

EAR
-WAR
--input.txt
--META-INF
--WEB-INF
---classes
(and so on)

I am trying to read input.txt from one of the classes (say abc.xyz.Myclass) in WEB-INF/classes folder. Here is what I tried:

this.getClass().getClassLoader().getResourceAsStream("../../input.txt");

and

Thread.currentThread().getContextClassLoader().getResourceAsStream("../../input.txt");

I tried several paths like "../input.txt" or "/input.txt" or just "input.txt" by attaching a debugger. But every time I am getting NULL as return value (means it is not able to find the file).

What is the correct way to access that file in war irrespective of whether war is deployed standalone or it is packed in ear? Please help.


回答1:


That is because input.txt is outside of the classpaths, one of which is typically WEB-INF/classes/, and you cannot access resources that is located outside the classpath using classloaders.

Alternatively, if the code can access the HttpServletRequest object:

    request.getServletContext().getResourceAsStream("/input.txt");

Of course there is other ways to obtain the ServletContext instance.




回答2:


When using getResource(), the resource needs to be on the classpath. Therefore you need to put input.txt somewhere under the classes directory.



来源:https://stackoverflow.com/questions/29819735/find-a-resource-txt-file-in-war-file-which-is-deployed-standalone-or-in-ear

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