當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java getPath()和getCanonicalPath()的區別用法及代碼示例

Java File getPath()用法及代碼示例方法是File類的一部分。此函數返回給定文件對象的路徑。該函數返回一個字符串對象,其中包含給定文件對象的路徑,而getCanonicalPath()方法是Path類的一部分。此函數返回給定文件對象的規範路徑名。如果文件對象的路徑名是Canonical,則它僅返回當前文件對象的路徑。規範路徑始終是絕對且唯一的,如果存在,該函數將從路徑中刪除“。”。現在,方法getPath()和getCanonicalPath()都屬於File類,並且都是獲取文件係統路徑的File方法。首先,我們從以下文件結構了解兩條路徑之間的區別。

圖解:考慮windows目錄下隨機路徑

|--D:
   \--Article      
   \--Test
   \--Program
       \--Python
       \--JAVA
           \Program1.java

如果通過了路徑“Python/../JAVA/Program1.java”,則Path和規範路徑的值如下所示。

  • Path:Python \ .. \ JAVA \ Program1.java
  • 規範路徑:d:\ Program \ JAVA \ Program1.java

現在讓我們了解兩種方法之間的區別

(A)理論差異



getPath()方法getCanonicalPath()方法
此函數以字符串形式返回抽象路徑名。此函數返回給定文件對象的規範路徑名。
返回的路徑名可能是絕對路徑。規範路徑始終是絕對且唯一的路徑。
如果使用String路徑名創建文件對象,則僅返回路徑名。如果需要,此方法首先將此路徑名轉換為絕對形式。為此,它將調用getAbsolutePath()方法,然後將其映射到其唯一形式。
如果在文件對象的參數中使用了URL,則它將刪除協議並返回文件名此方法刪除了多餘的名稱,例如 ” 。 “ 和 “.. ” 來自路徑名。它將解析符號鏈接並將驅動器號轉換為標準大小寫。
此方法不會引發任何異常。

此方法引發以下異常。

安全異常 :如果無法訪問所需的屬性值。

I /O異常:如果發生I /O異常。

例:

文件f =新文件(“ c:\\ users \\ .. \\ program \\。\\ file1.txt”)

路徑:-c:\ users \ .. \ program \。\ file1.txt

例:

文件f =新文件(“ c:\\ users \\ .. \\ program \\。\\ file1.txt”)

規範路徑:-c:\ program \ file1.txt

實施:(B)實際差異

示例

Java


// Java program to demonstrate the difference
// between getPath() and  getCanonicalPath() function
// Importing input output classes
import java.io.*;
// Class
public class GFG {
    // Main driver method
    public static void main(String args[])
    {
        // Try block to check exceptions
        try {
            // Creating a file object
            File f = new File(
                "g:\\gfg\\A(7)PATH\\Test\\..\\file1.txt");
            // Getting the Path of file object
            String path = f.getPath();
            // Getting the Canonical path of the file object
            String canonical = f.getCanonicalPath();
            // Display the file path of the file object
            // and also the Canonical path of file
            System.out.println("Path:" + path);
            System.out.println("Canonical path:"
                               + canonical);
        }
        // Catch block to handle if exception/s occurs
        catch (Exception e) {
            // Exception message is printed where occurred
            System.err.println(e.getMessage());
        }
    }
}

輸出:

Path (getPath()):g:\gfg\A(7)PATH\Test\..\file1.txt
path (getCanonicalPath()):G:\gfg\A(7)PATH\file1.txt




相關用法


注:本文由純淨天空篩選整理自meetsuvariya大神的英文原創作品 Difference Between getPath() and getCanonicalPath() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。