Bishoy Bishoy - 4 months ago 23
Java Question

FileNotFoundException when accessing a resource file after deploy to tomcat

I got two maven projects:


  1. A JAR with a resource file accessed from its code

  2. A WAR that has a RESTful service that uses the JAR



When the JAR unit tests run, it is able to access the resource file.

After deploying to tomcat, the access to the resource file fails with FileNotFoundException

I tried both these lines but the same results:

File file = new File(getClass().getClassLoader().getResource("file.xml").getFile());


And

File file = new File(getClass().getResource("/file.xml").getFile());


When debugging, I found the value of
file
is as following:

file:/usr/share/tomcat8/webapps/ROOT/WEB-INF/lib/com.projectgroup.projectname-1.0-SNAPSHOT.jar!/file.xml


I've opened the JAR at that location and found the file there. So any idea why this is happening.

Answer

Try to use getResourceAsStream() insteed of resource.getFile()

Another way to get your xml file loaded in your classpath is by using the Spring Framework as below:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:your/package/**/file.xml");
Comments