Javaexamples-file-compare

提供:Dev Guides
移動先:案内検索

Javaの例-ファイルパスの比較

問題の説明

2つのファイルのパスを比較するには?

溶液

この例は、Fileクラスのfilename.compareTo(別のファイル名)メソッドを使用して、同じディレクトリ内の2つのファイルのパスを比較する方法を示しています。

import java.io.File;

public class Main {
   public static void main(String[] args) {
      File file1 = new File("C:/File/demo1.txt");
      File file2 = new File("C:/java/demo1.txt");

      if(file1.compareTo(file2) == 0) {
         System.out.println("Both paths are same!");
      } else {
         System.out.println("Paths are not same!");
      }
   }
}

結果

上記のコードサンプルは、次の結果を生成します。

Paths are not same!