Java里各种路径的区别:getPath(), getCanonicalPath()

摘要: 写程序时,通常会听到各种不同的路径,比如:相对路径,绝对路径等. 对于 java 文件操作来说,一样有这些路径,在以前 没怎么注意到这个api: getCanonicalPath(),  其实这个东西很重要,因为这个api 是真正能拿到一个文件的唯一路径的api, 它的返回值一定是一个绝对路径.唯一指向一个文件.

写程序时,通常会听到各种不同的路径,比如:相对路径,绝对路径等. 对于 java 文件操作来说,一样有这些路径,在以前 没怎么注意到这个api: getCanonicalPath(), 其实这个东西很重要,因为这个api 是真正能拿到一个文件的唯一路径的api, 它的返回值一定是一个绝对路径.唯一指向一个文件.

getPath(), 这是相对路径,相对于当前操作文件的路径。getAbsolutePath() 返回绝对路径,但他返回的绝对路径不是唯一的,不像getCanonicalPath() 那样返回唯一的绝对路径. 比如如下:

C:\temp\test.txt
C:\temp\.\test.txt
C:\temp1\..\temp\test.txt

这些都是绝对路径,但只有 C:\temp\test.txt 是 getCanonicalPath() 返回的结果,唯一路径。用一个例子来看看返回的结果:
public class PathDemo {

    public static void main(String args[]) {
        System.out.println("Path of the given file :");
        File child = new File(".././Java.txt");
        displayPath(child);

        File parent = child.getParentFile();
        System.out.println("Path of the parent file :");
        displayPath(parent);
    }

    public static void displayPath(File testFile) {
        System.out.println("path : " + testFile.getPath());
        System.out.println("absolute path : " + testFile.getAbsolutePath());

        try {
            System.out.println("canonical path : " + testFile.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Output:
Path of the given file :
path : ..\.\Java.txt
absolute path : C:\Users\WINDOWS 8\workspace\Demo\..\.\Java.txt
canonical path : C:\Users\WINDOWS 8\workspace\Java.txt

Path of the parent file :
path : ..\.
absolute path : C:\Users\WINDOWS 8\workspace\Demo\..\.
canonical path : C:\Users\WINDOWS 8\workspace


看到没有,如果真正想要拿绝对路径,用 getCanonicalPath() 是个不错的方法. 另外在网上还看到有兄弟是这么总结的:

当输入为绝对路径时,返回的都是绝对路径。
当输入为相对路径时:
getPath()返回的是File构造方法里的路径,是什么就是什么,不增不减
getAbsolutePath()返回的其实是user.dir+getPath()的内容,从上面返回的结果可以得出。
getCanonicalPath()返回的就是标准的将符号完全解析的路径

上一篇: Java 取随机数的两种方法
下一篇: 在servlet中用spring @Autowire 注入.

Avatar

qianjinpianfang.com 评论于: 2014-09-19

很深奥的东西,只能以文字表达支持了。
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号