getPath getAbsolutePath和getCanonicalPath的區別
File的這三個方法在api中都有說明,僅以程序為例說明。
package test;
import java.io.File;
import java.io.IOException;
public class TestFilePath {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(System.getProperty("user.dir"));
try {
System.out.println("-----默認相對路徑:取得路徑不同------");
File file1 = new File("..//src//test1.txt");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getCanonicalPath());
System.out.println("-----默認相對路徑:取得路徑不同------");
File file = new File(".//test1.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println("-----默認絕對路徑:取得路徑相同------");
File file2 = new File("D://workspace//test//test1.txt");
System.out.println(file2.getPath());
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
程序執行結果如下:
F:/eclipseworkspace/testejb
-----默認相對路徑:取得路徑不同------
../src/test1.txt
F:/eclipseworkspace/testejb/../src/test1.txt
F:/eclipseworkspace/src/test1.txt
-----默認相對路徑:取得路徑不同------
./test1.txt
F:/eclipseworkspace/testejb/./test1.txt
F:/eclipseworkspace/testejb/test1.txt
-----默認絕對路徑:取得路徑相同------
D:/workspace/test/test1.txt
D:/workspace/test/test1.txt
D:/workspace/test/test1.txt
結論:
當輸入為絕對路徑時,返回的都是絕對路徑。
當輸入為相對路徑時:
getPath()返回的是File構造方法裏的路徑,是什麼就是什麼,不增不減
getAbsolutePath()返回的其實是user.dir+getPath()的內容,從上麵F:/eclipseworkspace/testejb、F:/eclipseworkspace/testejb/../src/test1.txt、F:/eclipseworkspace/testejb/./test1.txt可以得出。
getCanonicalPath()返回的就是標準的將符號完全解析的路徑
最後更新:2017-04-02 06:51:33