JAVA获得项目根路径
// 第一种:
File f = new File(Objects.requireNonNull(this.getClass().getResource("/")).getPath());
System.out.println("path1: "+f);
// 第二种:
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println("path2: "+courseFile);
// 第三种:
URL xmlPath = this.getClass().getClassLoader().getResource("");
System.out.println("path3: "+xmlPath);
// 第四种:
System.out.println("path4: " +System.getProperty("user.dir"));
// 第五种:
System.out.println("path5: "+System.getProperty("java.class.path").split(";")[0]);
// 第六种:
System.out.println("path6: "+Thread.currentThread().getContextClassLoader().getResource("").getPath());
// 第七种:
File f2 = new File(Objects.requireNonNull(this.getClass().getResource("")).getPath());
System.out.println("path7: "+f2);
// 第八种:
String path = "";
try {
path = ResourceUtils.getURL("classpath").getPath();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("path8: "+path);
输出的结果:
项目名:swagger-codegen 模块名:codegen-service
path1: D:\IDEAworkspace\swagger-codegen\codegen-service\target\classes
path2: D:\IDEAworkspace\swagger-codegen
path3: file:/D:/IDEAworkspace/swagger-codegen/codegen-service/target/classes/
path4: D:\IDEAworkspace\swagger-codegen
path5: C:\Program Files\java\jdk1.8.0_262\jre\lib\charsets.jar
path6: /D:/IDEAworkspace/swagger-codegen/codegen-service/target/classes/
path7: D:\IDEAworkspace\swagger-codegen\codegen-service\target\classes\com\codegen\codegenservice\controller
path8: /D:/IDEAworkspace/swagger-codegen/classpath