先说结论:
getPath方法,返回的和file类在初始化时候输入的参数基本一致
getAbsolutePath方法,返回的是绝对路径,不过在初始化时,如果输入了.或者..那么返回值里也包含.或者..
getCanonicalPath返回的是规范的绝对路径
验证该结论的程序和程序的输入见下文。
package files;
import java.io.File;
import java.io.IOException;
public class FilePathtest {
public static void main(String[] args){
//在输入绝对路径时候,三者是一样的
File file = new File("D:/test.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//只输入文件名时,getAbsolutePath和getCanonicalPath有一样
file = new File("test.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file = new File("./test.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
///
file = new File("./../test.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
该类的输出结果
D:/test.txt
D:/test.txt
D:/test.txt
test.txt
D:/workspace/test/test.txt
D:/workspace/test/test.txt
./test.txt
D:/workspace/test/./test.txt
D:/workspace/test/test.txt
./../test.txt
D:/workspace/test/./../test.txt
D:/workspace/test.txt