Java File 類的 getPath()、getAbsolutePath()、getCanonicalPath() 的區別

楔子

考慮一下幾種路徑:
C:\temp\file.txt- 絕對路徑,也是規範路徑
.\file.txt- 相對路徑
C:\temp\myapp\bin\..\..\file.txt這是一個絕對路徑,但不是規範路徑
關於什麼是規範路徑? 粗略的認爲規範路徑就是不包含相對路徑如..\或者.\絕對路徑

實例說明

package com.sino.daily.code_2020_3_11;

import java.io.File;

/**
 * create by 2020-05-31 08:46
 *
 * @author caogu
 */
public class TestFilePath {
    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("user.dir"));

        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());
    }
}

在這裏插入圖片描述

結論

  • 當輸入爲絕對路徑時,返回的都是絕對路徑。

  • 當輸入爲相對路徑時:

    getPath()返回的是File構造方法裏的路徑,是什麼就是什麼,不增不減

    getAbsolutePath()返回的其實是user.dir+getPath()的內容,從上面F:\eclipseworkspace\testejb、 F:\eclipseworkspace\testejb…\src\test1.txt、F:\eclipseworkspace\testejb.\test1.txt可以得出。

    getCanonicalPath()返回的就是標準的將符號完全解析的路徑,會返回絕對路徑,會把..\.\這樣的符號解析掉

建議

爲了防範安全風險,在做路徑校驗時,建議使用getCanonicalPath()

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