Compare two file paths in Java


Two file paths can be compared lexicographically in Java using the method java.io.File.compareTo(). This method requires a single parameter i.e.the abstract path name that is to be compared. It returns 0 if the two file path names are equal.

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) {
      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");
      }
   }
}

The output of the above program is as follows −

Output

Both the paths are lexicographically equal

Now let us understand the above program.

The method java.io.File.compareTo() is used to compare the two file paths lexicographically. If 0 is returned by the method, the file paths are lexicographically equal, otherwise not. A code snippet that demonstrates this is given as follows −

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements