Determine if two filename paths refer to the same File in Java


The method java.io.File.equals() is used to find if the two file names refer to the same File in Java. This method requires a single parameter i.e.the file object that is to be compared to the other file object. It returns if the file objects are same and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

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 output of the above program is as follows −

Output

The two file names refer to the same file? false

Now let us understand the above program.

The method java.io.File.equals() is used to find if the two file names refer to the same File in Java. The boolean value returned by the method is printed. A code snippet that demonstrates this is given as follows −

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();
}

Updated on: 30-Jul-2019

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements