java中File操作——getPath和getAbsolutePath和getCanonicalPath

getPath得到的是構造參數的路徑。

getAbsolutePath得到的是全路徑。如果構造參數是相對路徑,則返回當前目錄的絕對路徑+構造參數路徑;如果是絕對路徑則直接返回。

例子:

public void diff_pathAndAbsolutePath(){
    File file1 = new File(".\\test1.txt");
    File file2 = new File("D:\\workspace\\test\\test1.txt");
    System.out.println("-----默認相對路徑:取得路徑不同------");
    System.out.println(file1.getPath());
    System.out.println(file1.getAbsolutePath());
    System.out.println("-----默認絕對路徑:取得路徑相同------");
    System.out.println(file2.getPath());
    System.out.println(file2.getAbsolutePath());
}

結果:

-----默認相對路徑:取得路徑不同------
.\test1.txt
D:\workspace\test\.\test1.txt
-----默認絕對路徑:取得路徑相同------
D:\workspace\test\test1.txt
D:\workspace\test\test1.txt

getabsolutePath和getCononicalPath的區別

getCanonicalPath得到的不僅是全路徑,而且會解析並剔除[..]這樣的符號,即給出一個標準的絕對路徑。

例子:

public void diff_AbsolutePathAndCanonicalPath() throws IOException{
    File file = new File("..\\src\\test1.txt");
    System.out.println(file.getAbsolutePath());
    System.out.println(file.getCanonicalPath());
}
結果:

D:\workspace\test\..\src\test1.txt
D:\workspace\src\test1.txt




發佈了69 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章