当前位置:   article > 正文

Java File 类的 getPath()、getAbsolutePath()、getCanonicalPath() 的区别_java的file.getabsolutepath和自己设置的path不一样

java的file.getabsolutepath和自己设置的path不一样

楔子

考虑一下几种路径:
C:\temp\file.txt- 绝对路径,也是规范路径
.\file.txt- 相对路径
C:\temp\myapp\bin\..\..\file.txt这是一个绝对路径,但不是规范路径
关于什么是规范路径? 粗略的认为规范路径就是不包含相对路径如..\或者.\绝对路径

实例说明

package com.sino.daily.code_2020_3_11;

import java.io.File;

/**
 * create by 2020-05-31 08:46
 *
 * @author caogu
 */
public class TestFilePath {
    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("user.dir"));

        System.out.println("-----默认相对路径:取得路径不同------");
        File file1 = new File("..\\src\\test1.txt");
        System.out.println(file1.getPath());
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getCanonicalPath());

        System.out.println("-----默认相对路径:取得路径不同------");
        File file = new File(".\\test1.txt");
        System.out.println(file.getPath());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getCanonicalPath());

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

在这里插入图片描述

结论

  • 当输入为绝对路径时,返回的都是绝对路径。

  • 当输入为相对路径时:

    getPath()返回的是File构造方法里的路径,是什么就是什么,不增不减

    getAbsolutePath()返回的其实是user.dir+getPath()的内容,从上面F:\eclipseworkspace\testejb、 F:\eclipseworkspace\testejb…\src\test1.txt、F:\eclipseworkspace\testejb.\test1.txt可以得出。

    getCanonicalPath()返回的就是标准的将符号完全解析的路径,会返回绝对路径,会把..\.\这样的符号解析掉

建议

为了防范安全风险,在做路径校验时,建议使用getCanonicalPath()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/819896
推荐阅读
相关标签
  

闽ICP备14008679号