File类提供了getPath()、getAbsolutePath()、getCanonicalPath()三个方法来提供文件路径,本文将通过下面的实例演示它们的区别与联系:
public class FileTest {
static void printPath(String path){
System.out.println("输入:" + path);
File file = new File(path);
printPath(file);
}
static void printPath(File file){
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
System.err.println("Error occurs when invoking getCanonicalPath()");
}
System.out.println();
}
public static void main(String[] args) {
printPath("C:\\Users\\qwer\\Desktop\\osu\\图解HTTP.pdf");
printPath("图解HTTP.pdf");
printPath(".\\图解HTTP.pdf");
printPath("..\\不存在的目录\\图解HTTP.pdf");
}
}
结果为:
输入:C:\Users\qwer\Desktop\osu\图解HTTP.pdf
C:\Users\qwer\Desktop\osu\图解HTTP.pdf
C:\Users\qwer\Desktop\osu\图解HTTP.pdf
C:\Users\qwer\Desktop\osu\图解HTTP.pdf
输入:图解HTTP.pdf
图解HTTP.pdf
D:\eclipsepreferences\Tests\图解HTTP.pdf
D:\eclipsepreferences\Tests\图解HTTP.pdf
输入:.\图解HTTP.pdf
.\图解HTTP.pdf
D:\eclipsepreferences\Tests\.\图解HTTP.pdf
D:\eclipsepreferences\Tests\图解HTTP.pdf
输入:..\不存在的目录\图解HTTP.pdf
..\不存在的目录\图解HTTP.pdf
D:\eclipsepreferences\Tests\..\不存在的目录\图解HTTP.pdf
D:\eclipsepreferences\不存在的目录\图解HTTP.pdf
用于测试的路径中,第一个是绝对路径,后三个都是相对路径。从输出结果中,可以得出几点结论:
(1)对于绝对路径,三种方法的输出结果相同。
(2)对于相对路径,getPath()不做任何处理,输出路径等于输入路径;getAbsolutePath()简单地将当前工作目录(即项目文件夹路径,本文中为D:\eclipsepreferences\Tests\)与输入的相对路径拼接在一起,包括.\与..\;getCanonicalPath()会在getAbsolutePath()的基础上解析出完整的路径。
(3)Java中,相对路径的根默认在项目文件夹路径。
(4)getCanonicalPath()返回的必定是绝对路径。