在 Java 中比較兩個檔案路徑


可以使用 java.io.File.compareTo() 方法在 Java 中按字典順序比較兩個檔案路徑。該方法需要一個引數,即要比較的抽象路徑名。如果兩個檔案路徑名相等,則返回 0。

下面給出了一個演示的程式 -

示例

 線上演示

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file1 = new File("C:/File/demo1.txt");
      File file2 = new File("C:/File/demo1.txt");
      if (file1.compareTo(file2) == 0) {
         System.out.println("Both the paths are lexicographically equal");
      } else {
         System.out.println("Both the paths are lexicographically not equal");
      }
   }
}

以上程式的輸出如下 -

輸出

Both the paths are lexicographically equal

現在讓我們來理解一下上面的程式。

方法 java.io.File.compareTo() 用於按字典順序比較兩個檔案路徑。如果方法返回 0,則檔案路徑按字典順序相等,否則不相等。下面給出了一個演示程式碼段 -

File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/File/demo1.txt");
if (file1.compareTo(file2) == 0) {
   System.out.println("Both the paths are lexicographically equal");
} else {
   System.out.println("Both the paths are lexicographically not equal");
}

更新日期: 2019 年 7 月 30 日

831 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告