java中File操作——getPath和getAbsolutePath和getCanonicalPath

本文详细介绍了Java中File类的getPath()、getAbsolutePath()与getCanonicalPath()方法的区别及使用场景。通过实例展示了如何获取文件的相对路径、绝对路径以及标准化后的绝对路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getPath得到的是构造参数的路径。

getAbsolutePath得到的是全路径。如果构造参数是相对路径,则返回当前目录的绝对路径+构造参数路径;如果是绝对路径则直接返回。

例子:

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

结果:

-----默认相对路径:取得路径不同------
.\test1.txt
D:\workspace\test\.\test1.txt
-----默认绝对路径:取得路径相同------
D:\workspace\test\test1.txt
D:\workspace\test\test1.txt

getabsolutePath和getCononicalPath的区别

getCanonicalPath得到的不仅是全路径,而且会解析并剔除[..]这样的符号,即给出一个标准的绝对路径。

例子:

public void diff_AbsolutePathAndCanonicalPath() throws IOException{
    File file = new File("..\\src\\test1.txt");
    System.out.println(file.getAbsolutePath());
    System.out.println(file.getCanonicalPath());
}
结果:

D:\workspace\test\..\src\test1.txt
D:\workspace\src\test1.txt




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值