文章目录
xxx.class.getResource(“”)
获取class文件所在的具体目录。
// TestGetResource.java
// 当前包名为:com.loc
//获取当前class文件所在位置,以URL形式返回
URL url = getClass().getResource("");
//输出:file:/D:/dev/workspace/AnyTest/bin/com/loc/
System.out.println(url);
//去除file:前缀后剩下的部分:/D:/dev/workspace/AnyTest/bin/com/loc/
System.out.println(url.getPath());
xxx.class.getResource(“/”)
传入的/代表根目录,用于获取class文件的根目录(包名的起点)。
// TestGetResource.java
// 当前包名为:com.loc
//获取class文件根目录位置
url = getClass().getResource("/");
//file:/D:/dev/workspace/AnyTest/bin/
System.out.println(url);
///D:/dev/workspace/AnyTest/bin/
System.out.println(url.getPath());
xxx.class.getProtectionDomain().getCodeSource().getLocation()
- 如果是普通java项目,获取到的是class文件的根目录(包名起点)。
// TestGetResource.java
// 当前包名为:com.loc
//获取class文件根目录位置
URL srcLocation = getClass().getProtectionDomain().getCodeSource().getLocation();
//输出:file:/D:/dev/workspace/AnyTest/bin/
System.out.println(srcLocation);
//输出:/D:/dev/workspace/AnyTest/bin/
System.out.println(srcLocation.getPath());
- 如果是Web项目,获取到的是class文件的完整路径,包含
XXX.class文件名本身。
// TestGetResource.java
// 当前包名为:com.loc
//Web项目下,可用于获取class文件全路径
URL srcLocation = getClass().getProtectionDomain().getCodeSource().getLocation();
//输出:file:/D:/dev/.../WEB-INF/classes/com/loc/TestGetResource.class
System.out.println(srcLocation);
//输出:/D:/dev/.../WEB-INF/classes/com/loc/TestGetResource.class
System.out.println(srcLocation.getPath());
本文详细解释了如何在Java中使用getClass().getResource()方法获取class文件路径,区分了不同场景下的行为:普通项目与Web项目的区别,以及通过.class.getProtectionDomain().getCodeSource().getLocation()获取完整路径。
617

被折叠的 条评论
为什么被折叠?



