问题描述
我的webapp中有这样的文件结构:
I have a file structure like this in my webapp:
webapp/
├── META-INF
└── WEB-INF
├── reports
│ └── info.txt
└── web.xml
3 directories, 2 files
我需要 / WEB-INF / reports / info。 txt
来自类似的类:
this.getClass().getResource("/WEB-INF/reports/info.txt");
这会解决吗?我要测试它,但我不确定Tomcat的类加载器如何解决问题。如果这不起作用,我该如何获取文件?
Will this resolve? I'm going to test it, but I'm not sure how Tomcat's classloader resolves things. If this doesn't work, how can I get the file?
推荐答案
好吧,首先, this.getClass()。getResource
不应该工作(虽然我没有尝试)。它不是类路径,它是一个ServletContext,所以你需要使用 ServletContext.getResource
。
Well, first of all, this.getClass().getResource
should not work (though I didn't try). It's not a classpath, it's a ServletContext, so you need to use ServletContext.getResource
.
问题是,它不一定是文件:它可以是WAR存档中的条目。所以取决于你究竟知道什么,答案可能会有所不同。
Problem is, it is not necessary a file: it can be an entry in a WAR archive. So depending on what exactly you know, the answer may be different.
我们使用Spring实用程序类处理这两个文件(通过 ServletContext.getResourcePaths
如果可用)和WAR(通过 ServletContext.getResource
)。如果你使用Spring,那可能是最好的方法。如果不这样做,您可能需要重新实现该解决方案。
We use a Spring utility class which handles both files (via ServletContext.getResourcePaths
if available) and WARs (via ServletContext.getResource
). If you use Spring, that may be the best way. If you don't, you'll probably need to re-implement the solution.
或者,您只需使用 ServletContext.getResourceAsStream
-it并不关心资源的存储位置。所以只要你需要它的内容而不是路径,你应该没问题。
Alternatively, you cal simply use ServletContext.getResourceAsStream
—it doesn't care where exactly the resource is stored. So as long as you need its content and not the path, you should be fine.
这篇关于从getResource解析webapp的根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!