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

被折叠的 条评论
为什么被折叠?



