简体   繁体   English

如何从servlet到达www目录中的文件?

[英]how to reach a file in www directory from a servlet?

Using tomcat 6, i created a template inside www/templates/templatefile.html 使用tomcat 6,我在www / templates / templatefile.html内创建了一个模板

how do I access it from a servlet ? 如何从servlet访问它? i want to read the html file and parse it. 我想阅读HTML文件并进行解析。

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. 我尝试使用request.getRealPath(request.getServletPath())获取真实路径,然后从那里转到模板目录,但是由于某种原因,它仍然找不到文件。

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: 假设www是公共Web内容根目录中的文件夹,则可以使用ServletContext#getRealPath()将相对Web路径转换为绝对磁盘文件系统路径,如下所示:

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). 请注意,当不扩展WAR时,这将不起作用(默认修剪中的Tomcat可以这样做,但可以将其配置为不这样做)。 If all you want to end up is having an InputStream of it, then you'd rather like to use ServletContext#getResourceAsStream() instead. 如果要结束的全部是InputStream ,那么您想使用ServletContext#getResourceAsStream()代替。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM