Java获取类路径的方式

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:... (太长省略)

灰灰

原文地址:https://www.cnblogs.com/aixing/p/13327505.html