部署到 tomcat 后访问资源文件时出现 FileNotFoundException
FileNotFoundException when accessing a resource file after deploy to tomcat
我有两个maven项目:
- 一个 JAR,其中包含可从其代码访问的资源文件
- 具有使用 JAR
的 RESTful 服务的 WAR
当 JAR 单元测试 运行 时,它能够访问资源文件。
部署到 tomcat 后,访问资源文件失败并出现 FileNotFoundException
我尝试了这两行,但结果相同:
File file = new File(getClass().getClassLoader().getResource("file.xml").getFile());
和
File file = new File(getClass().getResource("/file.xml").getFile());
调试时发现file
的值如下:
file:/usr/share/tomcat8/webapps/ROOT/WEB-INF/lib/com.projectgroup.projectname-1.0-SNAPSHOT.jar!/file.xml
我在那个位置打开了 JAR 并在那里找到了文件。所以知道为什么会这样。
您的文件必须位于 war 文件的类路径中,它是否作为构建过程的一部分打包到 war 中?
尝试使用 getResourceAsStream()
而不是 resource.getFile()
另一种在类路径中加载 xml 文件的方法是使用 Spring 框架,如下所示:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:your/package/**/file.xml");
我有两个maven项目:
- 一个 JAR,其中包含可从其代码访问的资源文件
- 具有使用 JAR 的 RESTful 服务的 WAR
当 JAR 单元测试 运行 时,它能够访问资源文件。
部署到 tomcat 后,访问资源文件失败并出现 FileNotFoundException
我尝试了这两行,但结果相同:
File file = new File(getClass().getClassLoader().getResource("file.xml").getFile());
和
File file = new File(getClass().getResource("/file.xml").getFile());
调试时发现file
的值如下:
file:/usr/share/tomcat8/webapps/ROOT/WEB-INF/lib/com.projectgroup.projectname-1.0-SNAPSHOT.jar!/file.xml
我在那个位置打开了 JAR 并在那里找到了文件。所以知道为什么会这样。
您的文件必须位于 war 文件的类路径中,它是否作为构建过程的一部分打包到 war 中?
尝试使用 getResourceAsStream()
而不是 resource.getFile()
另一种在类路径中加载 xml 文件的方法是使用 Spring 框架,如下所示:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:your/package/**/file.xml");