How to find the working folder of a servlet based application in order to load resources
You could use ServletContext#getRealPath()
to convert a relative web content path to an absolute disk file system path.
String relativeWebPath = "/WEB-INF/static/file1.ext";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
However, if your sole intent is to get an InputStream
out of it, better use ServletContext#getResourceAsStream()
instead because getRealPath()
may return null
whenever the WAR is not expanded into local disk file system but instead into memory and/or a virtual disk:
String relativeWebPath = "/WEB-INF/static/file1.ext";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
This is much more robust than the java.io.File
approach. Moreover, using getRealPath()
is considered bad practice.
See also:
- getResourceAsStream() vs FileInputStream
- What does servletcontext.getRealPath("/") mean and when should I use it
- Where to place and how to read configuration resource files in servlet based application?
- Recommended way to save uploaded files in a servlet application