getPath()
这个是获取定义时的路径,这个没有什么争议的。
getAbsolutePath()
这个是获取绝对路径也就是其父路径 + “定义时的路径”,不会处理".\\","..\\"
getCanonicalPath()
获取规范化的绝对路径,会处理".\\","..\\" 等
public class mymain {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("ooooooooooooo\n");
//for(;;){}
String path = ".\\LXL.txt";
File file = new File(path);
try {
System.out.println(file.getCanonicalPath());
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出:
ooooooooooooo
D:\soft4dev\eclipse-workspace\test\LXL.txt
.\LXL.txt
D:\soft4dev\eclipse-workspace\test\.\LXL.txt
如果将 代码修改:
public class mymain {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("ooooooooooooo\n");
//for(;;){}
String path = "..\\LXL.txt";
File file = new File(path);
try {
System.out.println(file.getCanonicalPath());
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}输出:
ooooooooooooo
D:\soft4dev\eclipse-workspace\LXL.txt
..\LXL.txt
D:\soft4dev\eclipse-workspace\test\..\LXL.txt
如果是:
public class mymain {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("ooooooooooooo\n");
//for(;;){}
String path = "D:\\LXL.txt";
File file = new File(path);
try {
System.out.println(file.getCanonicalPath());
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}输出:
D:\LXL.txt
D:\LXL.txt
D:\LXL.txt
本文通过几个示例对比了Java中File类的getPath()、getAbsolutePath()与getCanonicalPath()方法的区别,解释了它们如何处理相对路径和特殊符号如'.'和'..'。
517

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



