Java I/O How to - Check If Two Filename Paths Refer to the Same File








Question

We would like to know how to check If Two Filename Paths Refer to the Same File.

Answer

    //  w  w w . j  av a2  s. c  o m

import java.io.File;

public class Main {
  public static void main(String[] argv) throws Exception {

    File file1 = new File("./filename");
    File file2 = new File("filename");
    System.out.println(file1.equals(file2));

    file1 = file1.getCanonicalFile();
    file2 = file2.getCanonicalFile();
    System.out.println(file1.equals(file2));
  }
}

The code above generates the following result.