在web开发中,如果需要配置额外的xml属性文件。有时在本地运行正常,但是部署到liunx上配置文件会发生找不到等现象。
有可能是获取本地路径时异常。下面介绍几种获取当前项目运行路径的方法。
1、URL url = T.class.getProtectionDomain().getCodeSource().getLocation();
例如:
URL url = CrmBussinessCodeXmlResolver.class.getProtectionDomain().getCodeSource().getLocation();
本地使用jetty启动获取到的路径是:file:/D:/workspace/bsm-server-njgd/target/classes/
使用本地tomcat启动路径:file:/E:/apache-tocmat2/webapps/bsm-server/WEB-INF/classes/
放入服务器liunx的 tomcat仲的路径时:/home/app/tomcat/bsm-server/webapps/bsm-server/WEB-INF/classes/
通过截取字段可以获取到响应的路径
if (path.startsWith("zip")) {// 当class文件在war中时,此时返回zip:D:/...这样的路径
path = path.substring(4);
} else if (path.startsWith("file")) {// 当class文件在class文件中时,此时返回file:/D:/...这样的路径
path = path.substring(6);
} else if (path.startsWith("jar")) {// 当class文件在jar文件里面时,此时返回jar:file:/D:/...这样的径
path = path.substring(10);
}
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}