File類的getPath()、getAbsolutePath()、getCanonicalPath()

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()返回的必定是絕對路徑。

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