ufk
ufk

Reputation: 32104

how to reach a file in www directory from a servlet?

Using tomcat 6, i created a template inside www/templates/templatefile.html

how do I access it from a servlet ? i want to read the html file and parse it.

I tried getting the real path using request.getRealPath(request.getServletPath()) and from there to go to the templates directory but for some reason it still can't find the file.

Upvotes: 0

Views: 164

Answers (1)

BalusC
BalusC

Reputation: 1108772

Assuming that www is a folder in the public web content root, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path as follows:

String relativeWebPath = "/www/templates/templatefile.html";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

Note that this won't work when the WAR is not expanded (Tomcat in default trim does it, but it can be configured not to do that). If all you want to end up is having an InputStream of it, then you'd rather like to use ServletContext#getResourceAsStream() instead.

String relativeWebPath = "/www/templates/templatefile.html";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

Upvotes: 3

Related Questions