开发者

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

开发者 https://www.devze.com 2023-03-14 05:05 出处:网络
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.

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);
// ...
0

精彩评论

暂无评论...
验证码 换一张
取 消