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!
You could use
ServletContext#getRealPath()to convert a relative web content path to an absolute disk file system path.However, if your sole intent is to get an
InputStreamout of it, better useServletContext#getResourceAsStream()instead becausegetRealPath()may returnnullwhenever the WAR is not expanded into local disk file system but instead into memory and/or a virtual disk:This is much more robust than the
java.io.Fileapproach. Moreover, usinggetRealPath()is considered bad practice.See also: