getPath(),getAbsolutePath(),getCanonicalPath() 區別

getPath:返回我們構造File的時候填充的路徑參數:eg:..\test.txt

public String getPath() {return path;}

getAbsolutePath:返回絕對路徑,路徑中如果包含.或者..不會進行路徑轉換,eg:G:\qsbk\..\test.txt

public String getAbsolutePath() {return fs.resolve(this);}

getCanonicalPath:返回規範化路徑名的絕對路徑,即:會將路徑中的.或者..進行最終轉換,例如上述的路徑結果是:eg:G:\test.txt

public String getCanonicalPath() throws IOException {
        if (isInvalid()) {
            throw new IOException("Invalid file path");
        }
        return fs.canonicalize(fs.resolve(this));
    }

下面我們看一個實例:

public static void main(String[] args) throws IOException {
        File file = new File("../test.txt");
        String str1 = file.getPath();
        System.out.println(str1);
        str1 = file.getAbsolutePath();
        System.out.println(str1);
        str1 = file.getCanonicalPath();
        System.out.println(str1);
    }

輸出:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章