程序如下:
package itheima02;
import org.junit.Test;
import java.io.File;
public class Demo04Path {
public static void main(String[] args) {
File f = new File("day18_08_05\\src\\config.properties");
System.out.println(f.getAbsolutePath());
//D:\IDEA\Java_Code\javaee354\day18_08_05\src\config.properties
}
@Test
public void getPath(){
File f = new File("day18_08_05\\src\\config.properties");
System.out.println(f.getAbsolutePath());
//D:\IDEA\Java_Code\javaee354\day18_08_05\day18_08_05\src\config.properties
}
@Test
public void getPath1(){
File f = new File("src\\config.properties");
System.out.println(f.getAbsolutePath());
//D:\IDEA\Java_Code\javaee354\day18_08_05\src\config.properties
}
}
项目中文件路径如图:
在main中我们得到文件的路径为:
//D:\IDEA\Java_Code\javaee354\day18_08_05\src\config.properties
方法getPath和main中的代码一致,结果得到的路径确不相同:
//D:\IDEA\Java_Code\javaee354\day18_08_05\day18_08_05\src\config.properties
多了一个项目路径:\day18_08_05
在getPath1方法中我们做了改进: File f = new File(“src\config.properties”);
去掉了项目路径,得到了我们想要的结果.
总结如下:
@Test单元测试会给路径多增加出一个day18_08_05路径
所以使用单元测试的时候要注意路径
带有路径操作的最好在main方法里边执行