java 读取相对路径 (resin / tomcat)

//TODO tomcat的相对路径
/*String path = "../webapps/lbh5/WEB-INF/config.properties";
File file = new File(path);
String absolutePath = file.getAbsolutePath();
System.out.println("absolutePath:"+absolutePath);*/

//TODO resin的相对路径
String path = "webapps/lbh5/WEB-INF/config.properties";
File file = new File(path);
String absolutePath = file.getAbsolutePath();
System.out.println("absolutePath:"+absolutePath);

//测试
String sysPath = System.getProperty("user.dir");
System.out.println("sysPath:"+sysPath);

绝对路径:

//TODO windows 重新封装路径
String path = String.valueOf(CommonVariable.class.getClassLoader().getResource(""));
System.out.println("path:"+path);
path = path.replace('/', '\'); // 将/换成
path = path.replace("file:", ""); //去掉file:
path = path.replace("classes\", ""); //去掉class
path = path.substring(1); //去掉第一个\,如 D:JavaWeb...
path += "config.properties";
System.out.println("path22:"+path);

原文地址:https://www.cnblogs.com/LiuB/p/7474765.html