Java下的路径getPath,getAbsolutePath和getCanonicalPath「终于解决」

Java (86) 2023-06-24 20:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说Java下的路径getPath,getAbsolutePath和getCanonicalPath「终于解决」,希望能够帮助你!!!。

1、getPath

以构造路径作为返回值。

2、getAbsolutePath

以当前路径+构造路径作为返回值。

3、getCanonicalPath

以全路径作为返回值(如果构造路径包含.或..,会进行处理)

示例:

public static void test1(){
	File file1 = new File(".\\aa.txt");
    File file2 = new File("D:\\test\\aa.txt");
    System.out.println("-----默认相对路径:取得路径不同------");
    System.out.println(file1.getPath());
    System.out.println(file1.getAbsolutePath());
	System.out.println(file1.getCanonicalPath());
    System.out.println("-----默认绝对路径:取得路径相同------");
    System.out.println(file2.getPath());
    System.out.println(file2.getAbsolutePath());
	System.out.println(file2.getCanonicalPath());
}


得到的结果:
-----默认相对路径:取得路径不同------
.\aa.txt
D:\test\.\aa.txt
D:\test\aa.txt
-----默认绝对路径:取得路径相同------
D:\test\aa.txt
D:\test\aa.txt
D:\test\aa.txt

发表回复