java getpath()_Java里各种路径的区别:getPath(), getCanonicalPath()

本文详细介绍了Java中处理文件路径的不同方法,包括相对路径、绝对路径和唯一路径。强调了`getCanonicalPath()`方法在获取文件唯一绝对路径中的重要性,与`getPath()`和`getAbsolutePath()`的区别。通过示例代码展示了这些方法在不同路径情况下的应用,揭示了在实际编程中如何正确使用这些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()返回的就是标准的将符号完全解析的路径

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值