Thread.currentThread.getContextClassLoader() 就是这样产生的。 我们使用Thread.currentThread.setContextClassLoader() 可以为当前线程指定相应的ClassLoader,然后用get的方式来获取。
[java] view plain copy package com.jiepu.docbuildermanager; //http://www.cnblogs.com/yejg1212/p/3270152.html public class TestMain { //记得URLDecoder.decode(url.getPath(), "utf-8"); public static void main(String[] args) { // 当前类(class)所在的包目录 System.out.println(TestMain.class.getResource("")); // class path根目录 System.out.println(TestMain.class.getResource("/")); // TestMain.class在<bin>/testpackage包中 // 2.properties 在<bin>/testpackage包中 System.out.println(TestMain.class.getResource("2.properties")); // TestMain.class在<bin>/testpackage包中 // 3.properties 在<bin>/testpackage.subpackage包中 System.out.println(TestMain.class.getResource("subpackage/3.properties")); // TestMain.class在<bin>/testpackage包中 // 1.properties 在bin目录(class根目录) System.out.println(TestMain.class.getResource("/1.properties")); TestMain t = new TestMain(); System.out.println(t.getClass()); System.out.println(t.getClass().getClassLoader()); System.out.println(t.getClass().getClassLoader().getResource("")); System.out.println(t.getClass().getClassLoader().getResource("/"));//null } } [java] view plain copy public static String getProjectPath() throws Exception { URL url = GlobalTool.class.getProtectionDomain().getCodeSource() .getLocation(); String filePath = URLDecoder.decode(url.getPath(), "utf-8"); if (filePath.endsWith(".jar")) { filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1); } File file = new File(filePath); filePath = file.getAbsolutePath(); //System.out.println(ClassLoader.getSystemClassLoader().getResource("")); return filePath; } //http://www.cnblogs.com/yejg1212/p/3270152.html public static String getRealPathByClass() throws Exception { //GlobalTool.class.getResource("/") String realPath = Thread.currentThread().getClass().getResource("/") .getPath(); realPath = URLDecoder.decode(realPath, "utf-8"); System.out.println(realPath); return realPath; } public static String getRealPathByClassLoader() { // Thread.currentThread().getClass().getClassLoader().getResource("")=null String realPath = GlobalTool.class.getClassLoader().getResource("") .getPath(); try { realPath = URLDecoder.decode(realPath, "utf-8"); System.out.println(realPath); if (realPath.endsWith("!/config.properties")) { realPath = realPath.substring(0, realPath.lastIndexOf("!/config.properties")); } if (realPath.startsWith("file:/")) { realPath = realPath.substring("file:/".length()); } } catch (Exception e) { e.printStackTrace(); } return realPath; }