2019-11-18 java中File类getPath()、getAbsolutePath()的区别

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()区别?
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容