应用场景:将要操作的文件或者目录一同放在工程的某个目录下,连同工程一起部署放便管理。
最容易想到的方式为system.getProperty("user.dir");但是这种方法在发布情况和对于Eclipse的情况获取到的地址是不同的,已发布的动态web工程是system.getProperty("user.dir")值为:D:/eclipse/,对于Eclipse则是D:/workspace/test01/。
针对于这种情况我们大多数是要获取动态web工程的根目录地址,最后是这样获取根目录地址的。
public String getTemplatePath(){
String root = Thread.currentThread().getContextClassLoader().getResource("").toString();
System.out.println("getTemplatePath:--------"+root);
return root.substring(root.indexOf("file")+"file".length()+2);
}
返回的值为D:/IDE/apache-tomcat-6.0.43/wtpwebapps/devplatform/WEB-INF/classes/,然后根据自己文件/目录存放的位置进行调整地址