Home » Java » File path to resource in our war/WEB-INF folder?

File path to resource in our war/WEB-INF folder?

Posted by: admin November 30, 2017 Leave a comment


I’ve got a file in my war/WEB-INF folder of my app engine project. I read in the FAQs that you can read a file from there in a servlet context. I don’t know how to form the path to the resource though:


How would I construct my path to that resource to use with File(), just as it looks above?



There’s a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");


That will get you the full system path to the resource you are looking for. However, that won’t work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext’s getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");


The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet’s init() method. If you store it at that time, you can get your ServletContext any time you want after that.


Now with Java EE 7 you can find the resource more easily with

InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");