说明:getWebRootAbsolutePath(),getRootPath()这2个在linux和windows下都好使
import java.io.File;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
new Test().test();
}
public void test(){
String pathStr = this.getClass().getClassLoader().getResource("").getPath();
System.out.println("----pathStr:"+pathStr);
// 对 Windows 下获取 物理路径 做 特殊处理
if("\\".equals(File.separator)) {
pathStr = pathStr.substring(1).replaceAll("/", "\\\\");
}
System.out.println("----pathStr111:"+pathStr);
System.out.println("----3333:"+this.getClass().getResource("/").getPath());
System.out.println("---44"+this.getClass().getResource("/"));
System.out.println("---5"+Thread.currentThread().getContextClassLoader().getResource(""));
System.out.println("---6"+Test.class.getClassLoader().getResource(""));
System.out.println("---7"+ClassLoader.getSystemResource(""));
System.out.println("---8"+Test.class.getResource(""));
System.out.println("---9"+Test.class.getResource("/"));
//Class文件所在路径
System.out.println("--10"+new File("/").getAbsolutePath());
System.out.println("--11"+System.getProperty("user.dir"));
System.out.println("--12"+getRootPath());
// System.out.println("--13"+ApplicationContextHolder.getInstance().getClass().getResource("").getPath());
System.out.println("--14"+getWebRootAbsolutePath());
}
public String getWebRootAbsolutePath() {
String path = null;
String folderPath = Test.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
if (folderPath.indexOf("WEB-INF") > 0) {
path = folderPath.substring(0, folderPath
.indexOf("WEB-INF"));
}
return path;
}
public static String getRootPath(){
//因为类名为"Application",因此" Application.class"一定能找到
String result = Test.class.getResource("Test.class").toString();
int index = result.indexOf("WEB-INF");
if(index == -1){
index = result.indexOf("bin");
}
result = result.substring(0,index);
if(result.startsWith("jar")){
// 当class文件在jar文件中时,返回"jar:file:/F:/ ..."样的路径
result = result.substring(10);
}else if(result.startsWith("file")){
// 当class文件在class文件中时,返回"file:/F:/ ..."样的路径
result = result.substring(6);
}
if(result.endsWith("/"))result = result.substring(0,result.length()-1);//不包含最后的"/"
return result;
}
}