29.获取类路径的常见方式

一灰灰blogJava编程技巧JDK编程技巧约 390 字大约 1 分钟

实战29:获取类路径的常见方式

1. 资源路径查询

在Java环境中,如何获取当前类的路径,如何获取项目根路径,可以说是比较常见的需求场景了,下面简单的记录一下

@Test
public void showURL() throws IOException {
    // 第一种:获取类加载的根路径
    File f = new File(this.getClass().getResource("/").getPath());
    System.out.println(f);

    // 获取当前类的所在工程路径; 如果不加“/”  获取当前类的加载目录
    File f2 = new File(this.getClass().getResource("").getPath());
    System.out.println(f2);

    // 第二种:获取项目路径
    File directory = new File("");// 参数为空
    String courseFile = directory.getCanonicalPath();
    System.out.println(courseFile);


    // 第三种:根据系统资源获取
    URL xmlpath = this.getClass().getClassLoader().getResource("");
    System.out.println(xmlpath);


    // 第四种:系统变量
    System.out.println(System.getProperty("user.dir"));

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

输出如下:

/Users/user/Project/hui/testApp/pair/target/test-classes
/Users/user/Project/hui/testApp/pair/target/test-classes/net/finbtc/coin/test
/Users/user/Project/hui/testApp/pair
file:/Users/user/Project/hui/testApp/pair/target/test-classes/
/Users/user/Project/hui/testApp/pair
/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar:... (太长省略)

2. 小结

  1. new File(this.getClass().getResource("/").getPath())
    • 获取类加载的根路径
  2. new File(this.getClass().getResource("").getPath())
    • 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录
  3. new File("").getCanonicalPath()
    • 获取项目路径
  4. this.getClass().getClassLoader().getResource("")
  5. System.getProperty("user.dir")
  6. System.getProperty("java.class.path")
    • 获取所有的类路径 包括jar包的路径
Loading...