废话不多说,来个示例大家都懂了!
public class Demo1 {
public static void main(String[] args) throws IOException {
File file = new File("../2.txt");
file.createNewFile();
System.out.println(file.getPath());
//打印结果: ..\2.txt
System.out.println(file.getAbsolutePath());
//打印结果: E:\JAVA_CODE\2022\test_8_25\..\2.txt
System.out.println(file.getCanonicalPath());
//打印结果: E:\JAVA_CODE\2022\2.txt
}
}
如果新件File示例是根据绝对路径来创建的,那么这三个函数打印的结果是相同的
public class Demo1 {
public static void main(String[] args) throws IOException {
File file = new File("E:\html\demo\img");
file.createNewFile();
System.out.println(file.getPath());
//打印结果为: E:\html\demo\img
System.out.println(file.getAbsolutePath());
//打印结果为: E:\html\demo\img
System.out.println(file.getCanonicalPath());
//打印结果为: E:\html\demo\img
}
}