File 类的 getPath()、getAbsolutePath()、getCanonicalPath() 的区别【转】

File 类的 getPath()、getAbsolutePath()、getCanonicalPath() 的区别

感谢大佬:https://blog.csdn.net/zsensei/article/details/79365348

考虑一下几种路径:

  • C:\temp\file.txt - 绝对路径,也是规范路径
  • .\file.txt - 相对路径
  • C:\temp\myapp\bin\..\..\file.txt 这是一个绝对路径,但不是规范路径

关于什么是规范路径可参考 What’s a “canonical path”?

粗略的认为规范路径就是不包含相对路径如 …\ 或者 .\ 的绝对路径
看一个例子:

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.././file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}

上面的代码会输出

test…\file.txt
C:\projects\sandbox\trunk\test…\file.txt
C:\projects\sandbox\trunk\file.txt

由此可得出结论:

  • getPath() 方法跟创建 File 对象时传入的路径参数有关,返回构造时传入的路径
  • getAbsolutePath() 方法返回文件的绝对路径,如果构造的时候是全路径就直接返回全路径,如果构造时是相对路径,就返回当前目录的路径 + 构造 File 对象时的路径
  • getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉

参考:
What’s the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

posted @ 2019-07-29 16:19  超级小白龙  阅读(372)  评论(0编辑  收藏  举报