Java 从getResource解析webapp的根目录

Java 从getResource解析webapp的根目录,java,tomcat,classloader,Java,Tomcat,Classloader,我在我的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"); 这能解决问题吗?我将测试它,但我不确定To

我在我的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的类加载器是如何解决问题的。如果这不起作用,我怎样才能得到文件

首先,
this.getClass().getResource
不应该工作(尽管我没有尝试)。它不是类路径,而是ServletContext,因此需要使用
ServletContext.getResource

问题是,它不需要一个文件:它可以是战争档案中的一个条目。因此,根据你确切知道的情况,答案可能会有所不同

我们使用一个Spring实用程序类来处理文件(通过
ServletContext.getResourcePath
如果可用)和WAR(通过
ServletContext.getResource
)。如果你使用弹簧,那可能是最好的方法。如果不这样做,您可能需要重新实现解决方案


或者,您只需使用
ServletContext.getResourceAsStream
——它不关心资源的确切存储位置。因此,只要您需要它的内容而不是路径,您就可以了。

不,它无法解决问题
Class.getResource
从类路径加载资源,并且webapp的根目录本身不在类路径上

为了获得该资源,您需要获得
ServletContext
,然后可以调用
ServletContext.getResource(“/WEB-INF/reports/info.txt”)
。这应该行得通

您可以使用
Servlet.getServletConfig().getServletContext()
获取
ServletContext

或者,将您的
报告
目录移动到
/WEB-INF/classes
目录下(位于classpath上)。然后,您可以使用

getClass().getResource("reports/info.txt");

是的,所以问题是我需要它在servlet容器内外工作。我需要一个非常标准的API,无论我是在Tomcat中还是在Eclipse的jUnit类路径中,它都能让我获得一个给定的路径。您使用的API是什么?我使用的是Spring 3。如果您需要它在容器外部,请将资源保留在类路径中,不要接触Servlet API。使用Spring的
ResourceLoader
/
ApplicationContext
加载文件。令人敬畏:)