確定 Java 中的兩個檔名路徑是否指向同一檔案


java.io.File.equals() 方法用於判斷 Java 中兩個檔名是否指向同一檔案。此方法需要一個引數,即要與另一個檔案物件進行比較的檔案物件。如果檔案物件相同,則返回真,否則返回假。

演示此方法的程式如下 −

示例

 線上演示

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file1 = new File("demo1.txt");
         File file2 = new File("demo2.txt");
         boolean flag = file1.equals(file2);
         System.out.print("The two file names refer to the same file? " + flag);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

以上程式的輸出如下 −

輸出

The two file names refer to the same file? false

現在讓我們瞭解一下以上程式。

java.io.File.equals() 方法用於判斷 Java 中兩個檔名是否指向同一檔案。列印由該方法返回的布林值。演示此方法的程式碼片段如下 −

try {
   File file1 = new File("demo1.txt");
   File file2 = new File("demo2.txt");
   boolean flag = file1.equals(file2);
   System.out.print("The two file names refer to the same file? " + flag);
} catch(Exception e) {
   e.printStackTrace();
}

更新於: 30-Jul-2019

807 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告