package com.lening.getpath;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* @Author WangEn
* @CreateTime: 2021-04-10-12-20
* @Emile: wen_5988@163.com
*/
public class TestGetProjectPath {
// 获取编译后的路径
@Test
public void getPath1(){
// 第一种:获取类加载的根路径 D:\git\daotie\daotie\target\classes
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
}
@Test
public void getPath2(){
// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:\git\daotie\daotie\target\classes\my
File f2 = new File(this.getClass().getResource("").getPath());
System.out.println(f2);
}
@Test
public void getPath3() throws IOException {
// 第二种:获取项目路径 D:\git\daotie\daotie
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile+"\\pro");
}
@Test
public void getPath4() throws IOException {
// 第三种: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath = this.getClass().getClassLoader().getResource("");
System.out.println(xmlpath);
}
@Test
public void getPath5() throws IOException {
// 第四种: D:\git\daotie\daotie
System.out.println(System.getProperty("user.dir"));
}
@Test
public void getPath6(){
// 第五种: 获取所有的类路径 包括jar包的路径
System.out.println(System.getProperty("java.class.path"));
}
}
原文:https://www.cnblogs.com/WangEn/p/14640581.html