Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get real path for file in my WebContent folder?

I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the real path to this file in WebContent directory.

I use Spring Framework, so solution should be possible to make in Spring.

like image 379
newbie Avatar asked May 07 '10 05:05

newbie


2 Answers

If you need this in a servlet then use getServletContext().getRealPath("/filepathInContext")!

like image 70
Shyam Avatar answered Sep 22 '22 15:09

Shyam


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

In this case 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");
like image 45
A Kunin Avatar answered Sep 26 '22 15:09

A Kunin