java类获取web应用的根目录
Java中获取web应用的根目录的方法有两种,分别是:
一、在servlet可以用一下方法取得:
request.getRealPath(“/”)
例如:filepach = request.getRealPath(“/”)+”//upload//”;
二、不从jsp,或servlet中获取,只从普通java类中获取:
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
saxReader = new SAXReader();
if(path.indexOf(“WEB-INF”)>0){
path = path.substring(0,path.indexOf(“/WEB-INF/classes”)+16);// ‘/WEB-INF/classes’为16位
document = saxReader.read(path+filename);
}else{
document = saxReader.read(getClass().getResourceAsStream(filename));
}
weblogic tomcat 下都有效
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
必须是在非静态方法中才可以使用
