天天看点

Java获取类路径方法

参考原文:

  1. CSDN| Java获取类路径的方式:

    https://blog.csdn.net/An1090239782/article/details/82590011

  2. Java如何获取当前的jar包路径以及如何读取jar包中的资源:https://www.cnblogs.com/zeciiii/p/4178824.html

获取项目路径、类加载路径、当前类路径,和在jar包中运行的结果对比

public void printPath() throws IOException {
		/*
		 * 获取项目路径
		 */
		System.out.println("**获取项目路径**");
		System.out.print("\t1.利用File类提供的方法 获取项目路径-----\n\t");
		//1. (利用File类提供的方法 获取项目路径)
		File directory = new File("");// 参数为空
		String courseFile = directory.getCanonicalPath();
		System.out.println(courseFile);
		
		System.out.print("\t2.System.getProperty()函数获取项目路径-----\n\t");
		//2. (System.getProperty()函数获取项目路径)
		String property = System.getProperty("user.dir");
		System.out.println(property);
		
		
		/*
		 * 获取类加载根路径(classes目录)
		 */
		System.out.println("**获取类加载根路径classes**");
		System.out.print("\t3.使用getClass().getResource(\"/\")方法-----\n\t");
		//3. (使用getClass().getResource("/")方法)
		URL path_1 = this.getClass().getResource("/");//返回URL的对象,路径前方以file:开头,并且以"/"做目录间隔
		System.out.println(path_1);//  file:/D:/work/workspace_set/workspace_javaee/ProjectJavaWay/target/classes/
		System.out.print("\t");
		String path_2 = this.getClass().getResource("/").getPath();//返回路径最前方和末尾均多一个"/",并且以"/"做目录间隔
		System.out.println(path_2);//  /D:/work/workspace_set/workspace_javaee/ProjectJavaWay/target/classes/
		System.out.print("\t");
		String path_3 = this.getClass().getResource("/").getFile();//.getFile()和.getPath()作用相同
		System.out.println(path_3);//  /D:/work/workspace_set/workspace_javaee/ProjectJavaWay/target/classes/
		System.out.print("\t");
		File file = new File(path_2);//用File对象处理后,会删除头尾的"/",并且将所有的以"\(反斜杠)"间隔目录
		System.out.println(file);//  D:\work\workspace_set\workspace_javaee\ProjectJavaWay\target\classes

		System.out.print("\t4.使用getClass().getClassLoader()方法-----\n\t");
		//4. (使用getClass().getClassLoader()方法)
		String classsesPath_1 = this.getClass().getClassLoader().getResource("").getPath();
		System.out.println(classsesPath_1);

		System.out.print("\t5.使用getClass().getProtectionDomain().getCodeSource()方法-----\n\t");
		//5. (使用getClass().getProtectionDomain().getCodeSource()方法)
		String classsesPath_2 = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		System.out.println(classsesPath_2);
		
		
		/*
		 * 获取当前类所在目录
		 */
		System.out.println("**6.获取当前类所在目录**");
		String classPath = this.getClass().getResource("").getPath();
		System.out.println(classPath);
		

		// 第五种:  获取所有的类路径 包括jar包的路径(...\classes和...\**.jar)
		System.out.println("**7.获取所有的类路径 包括jar包的路径(...\\classes和...\\**.jar)**");
		System.out.println(System.getProperty("java.class.path"));
	}
	
           

eclipse中执行获得输出内容如下:

Java获取类路径方法

将这个类打成jar包,运行结果如下:

Java获取类路径方法

发现出现问题,在jar包中时,

URL path_1 = this.getClass().getResource("/");

this.getClass().getClassLoader().getResource("");

,这两种方式获取到的值为null,因此导致后续出现空指针异常。

经过测试,发现只有1、2、5、7方式能够使用:

Java获取类路径方法