如何使用java代码获取一个类的加载路径及根路径呢?
下文笔者讲述使用java代码获取类加载路径和项目根路径的方法分享,如下所示
获取类加载路径
是我们日常开发中,常使用的功能
如:加载资源文件,读取一些配置模板
那么如何获取当前类的路径,然后依次获取其它资源信息呢?下文笔者将一一道来,如下所示
实现思路:
方式1:
借助File对象
方式2:
借助ClassLoader对象
例:
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestClass {
public static void main(String[] args) {
TestClass test = new TestClass();
try {
test.showPath();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showPath() throws IOException {
// 第一种:获取类加载的根路径 D:\\test\test\target\classes
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
//获取当前类的所在工程路径;
//如果不加“/” 获取当前类的加载目录 D:\\test\test\target\classes\my
File f2 = new File(this.getClass().getResource("").getPath());
System.out.println(f2);
//获取项目路径 D:\\test\test
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile);
//file:/D:\\test\test/target/classes/
URL xmlpath = this.getClass().getClassLoader().getResource("");
System.out.println(xmlpath);
//D:\\test\test
System.out.println(System.getProperty("user.dir"));
/*
* 结果: C:\Documents and Settings\Administrator\workspace\projectName
* 获取当前工程路径
*/
//获取所有的类路径
//包括jar包的路径
System.out.println(System.getProperty("java.class.path"));
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


