简体   繁体   English

在war文件中查找独立或在耳中部署的资源(.txt文件)

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

I have a war file is packaged in ear and deployed. 我有一个war文件打包在耳中并部署。 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. 我试图从WEB-INF / classes文件夹中的一个类(比如abc.xyz.Myclass)读取input.txt 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. 我通过附加调试器尝试了几个路径,如“../input.txt”或“/input.txt”或只是“input.txt”。 But every time I am getting NULL as return value (means it is not able to find the file). 但每次我得到NULL作为返回值(意味着它无法找到该文件)。

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. 请帮忙。

When using getResource() , the resource needs to be on the classpath. 使用getResource() ,资源需要位于类路径上。 Therefore you need to put input.txt somewhere under the classes directory. 因此,您需要将input.txt放在classes目录下的某处。

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. 这是因为input.txt在类路径之外,其中一个通常是WEB-INF/classes/ ,并且您无法使用类加载器访问位于类路径外部的资源。

Alternatively, if the code can access the HttpServletRequest object: 或者,如果代码可以访问HttpServletRequest对象:

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

Of course there is other ways to obtain the ServletContext instance. 当然还有其他方法可以获取ServletContext实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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