how to reach a file in www directory from a servlet?
Using tomcat 6, i created a template inside www/tem开发者_运维技巧plates/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.
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);
// ...
精彩评论