How to find the working folder of a servlet based application in order to load resources

37,019

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:

Share:
37,019
Erel Segal-Halevi
Author by

Erel Segal-Halevi

I am a faculty member in Ariel University, computer science department. My research topic is Fair Division of Land. It is related to the classic problem of fair cake-cutting, which is a multi-disciplinary topic connecting mathematics, economics and computer science, I am always happy to discuss any topic related to land division or fair cake-cutting. If you have a new idea in these topics and need a partner for brain-storming, feel free to email me at [email protected]. The answers I receive in the Stack Exchange websites are very useful, and I often cite them in papers. See my website for examples.

Updated on July 09, 2022

Comments

  • Erel Segal-Halevi
    Erel Segal-Halevi almost 2 years

    I write a Java servlet that I want to install on many instances of Tomcat on different servers. The servlet uses some static files that are packed with the war file under WEB-INF. This is the directory structure in a typical installation:

    - tomcat
    -- webapps
    --- myapp
    ---- index.html
    ---- WEB-INF
    ----- web.xml
    ----- classes
    ------ src
    ------- .....
    ----- MY_STATIC_FOLDER
    ------ file1
    ------ file2
    ------ file3
    

    How can I know the absolute path of MY_STATIC_FOLDER, so that I can read the static files?

    I cannot rely on the "current folder" (what I get in a new File(".")) because it depends on where the Tomcat server was started from, which is different in every installation!