在项目中文件上传、下载,以及加载配置文件等的时候都存在获取当前文件的相对路径或绝对路径的情况。在Tomcat中一般不存在不能获取文件路径的问题,但是在多服务器处理中,因服务器的不同而获取的路径方式不统一,从而导致获取文件路径等存在差异性。
代码如下
/**
* 通过类路径来取工程路
*
* @return
* @throws Exception
*/
private String getAbsolutePathByClass() throws Exception {
String webPath = this.getClass().getResource("/").getPath().replaceAll("^\\/", "");
webPath = webPath.replaceAll("[\\\\\\/]+", "/");
webPath = webPath.replaceAll("%20", " ");
if (webPath.matches("^[a-zA-Z]:.*?$")) {
} else {
webPath = "/" + webPath;
}
webPath += "/";
webPath = webPath.replaceAll("[\\\\\\/]+", "/");
// 直接META-INF/context.xml来判断路径是否正(本例当前是根据Tomcat 6.0数据库连接池配置文件来验证获取文件路径是否成功,在实际使用中可根据自己项目来处理)
File file = new File(webPath + "META-INF/context.xml");
if (file.exists() && file.isFile()) {
return webPath;
} else {
return null;
}
}
/**
* 通过struts servlet来取工程路径
*
* @return
*/
private String getAbsolutePathByResource() throws Exception {
URL url = this.getServletContext().getResource("/");
String path = new File(url.toURI()).getAbsolutePath();
if (!path.endsWith("\\") && !path.endsWith("/")) {
path += File.separator;
}
return path;
}
这样可以首先采用servlet方式来获取当前路径,在实际应用中也可以采用这样的方式(更具不同项目配置和代码编写方式决定):
String path = servlet.getServletContext().getRealPath("/");
在weblogic、websphere等服务器上面获取不到的情况下可以采用第二种方式,也即就是获取路径的时候多一个 if(){}
注意:在websphere中默认获取到的文件路径是不带最后一个[ \ ]或者[ / ]的,所以如果要支持websphere 建议加上如下代码
if (!path.endsWith("/")) {
path += File.separator;
}