tomcat webapps directory absolute path?

11,116

Solution 1

see ServletContext.getRealPath

Solution 2

see getServletContext().getRealPath("") - This way will not work if content is being made available from a .war archive.

In some cases we can use another way to get real path. This is example of getting a path to a properties file C:/Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties:

// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");

// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");

if (decoded.startsWith("/")) {
    // path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
    decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");
Share:
11,116
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have tomcat extract in one place and my webapps directory may be somewhere else. Then how to get absolute path of my web application? . I have my file handling programme inside webapps and i want to find absolute path of my webapps or my application directory(starting from c:/ or /home/use/ ../../webapp/mywebapplication like that ). Thing is I dont have control on who/where my application is going to be deployed ?