在独立部署或部署在war文件中的war文件中查找资源(.txt文件) [英] Find a resource (.txt file) in war file which is deployed standalone or in ear

查看:106
本文介绍了在独立部署或部署在war文件中的war文件中查找资源(.txt文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个战争文件打包在耳朵里并部署了。结构如下:

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)

我正在尝试从WEB-INF / classes文件夹中的一个类(例如abc.xyz.Myclass)中读取 input.txt 。这是我尝试的方法:

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

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

我尝试了多个路径,例如 ../input.txt或 /input.txt或通过附加调试器即可实现 input.txt。但是每次我将NULL作为返回值时(意味着它找不到文件)。

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.

推荐答案

这是因为 input.txt 在外部类路径,其中之一通常是 WEB-INF / 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.

或者,如果代码可以访问 HttpServletRequest 对象:

Alternatively, if the code can access the HttpServletRequest object:

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

当然,还有其他方法可以获取 ServletContext 实例。

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

这篇关于在独立部署或部署在war文件中的war文件中查找资源(.txt文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆