【发布时间】:2009-08-05 11:10:29
【问题描述】:
我在一个地方有 tomcat 提取,而我的 webapps 目录可能在其他地方。那么如何获取我的 Web 应用程序的绝对路径呢? .我在 webapps 中有我的文件处理程序,我想找到我的 webapps 或我的应用程序目录的绝对路径(从 c:/ 或 /home/use/ ../../webapp/mywebapplication 这样的开始)。问题是我无法控制我的应用程序将在谁/何处部署?
【问题讨论】:
我在一个地方有 tomcat 提取,而我的 webapps 目录可能在其他地方。那么如何获取我的 Web 应用程序的绝对路径呢? .我在 webapps 中有我的文件处理程序,我想找到我的 webapps 或我的应用程序目录的绝对路径(从 c:/ 或 /home/use/ ../../webapp/mywebapplication 这样的开始)。问题是我无法控制我的应用程序将在谁/何处部署?
【问题讨论】:
【讨论】:
请参阅 getServletContext().getRealPath("") - 如果内容可从 .war 存档中获取,则此方法将不起作用。
在某些情况下,我们可以使用另一种方式来获取真实路径。这是获取属性文件路径的示例 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");
【讨论】: