美文网首页
2019-11-18 java中File类getPath()、g

2019-11-18 java中File类getPath()、g

作者: 忆丶往 | 来源:发表于2019-11-18 13:43 被阅读0次
File file = new File(".\\src\\test.txt");
1、getPath():

返回定义时的路径,(就是你写什么路径,他就返回什么路径)

2、getAbsolutePath():

返回绝对路径,但不会处理“.”“..”的情况

3、getCanonicalPath():

返回的是规范化的绝对路径,相当于将getAbsolutePath()中的“.”“..”解析成对应的正确的路径

例一(使用:“.\”一个点路径)

        //文件本地路径:C:\Users\84695\Desktop\其他\test.docx

        File file = new File(".\\84695\\Desktop\\其他\\test.docx");
        System.out.println(file.getPath());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getCanonicalPath());

//输出结果:
.\84695\Desktop\其他\test.docx
E:\HX-projects\hh\.\84695\Desktop\其他\test.docx  
E:\HX-projects\hh\84695\Desktop\其他\test.docx              (项目路径:E:\HX-projects\hh)

例二(使用:“..\”两个点路径)

        //文件本地路径:C:\Users\84695\Desktop\其他\test.docx
        File file = new File("..\\84695\\Desktop\\其他\\test.docx");

//输出结果:
..\84695\Desktop\其他\test.docx
E:\HX-projects\hh\..\84695\Desktop\其他\test.docx
E:\HX-projects\84695\Desktop\其他\test.docx   (注意这个结果的路径,与一个点时不一样;因为他解析了“.”和“..”的情况。)

例三(使用文件绝对路径)

        //文件本地路径:C:\Users\84695\Desktop\其他\test.docx
        File file = new File("C:\\Users\\84695\\Desktop\\其他\\test.docx");

//输出结果:
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx

"./""../"的区别

/ :表示当前路径的根路径

./ :表示当前路径

../ :表示父级路径,当前路径所在的上一级路径
java中File类getPath()、getAbsolutePath()、getCanonicalPath()区别?

相关文章

网友评论

      本文标题:2019-11-18 java中File类getPath()、g

      本文链接:https://www.haomeiwen.com/subject/wjpvictx.html