Skip to content
Related Articles

Related Articles

Comparing Path of Two Files in Java
  • Last Updated : 26 Oct, 2020

The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program.

To compare the path of the file, compareTo() method of File Class is used. compareTo() method compares two abstract path-names lexicographically. The ordering defined by this method is dependent upon the operating system.

Parameters: This method requires a single parameter i.e.the abstract pathname that is to be compared. 

Return Value: This method returns 0 if the argument is equal to this abstract pathname, a negative value if the abstract pathname is lexicographically less than the argument, and a value greater than 0 if the abstract pathname is lexicographically greater than the argument respectively.

Example:



Java




// Comparing path of two files in Java
  
import java.io.File;
  
public class GFG {
    
    public static void main(String[] args)
    {
  
        File file1 = new File("/home/mayur/GFG.java");
        File file2 = new File("/home/mayur/file.txt");
        File file3 = new File("/home/mayur/GFG.java");
  
        // Path comparision
        if (file1.compareTo(file2) == 0) {
            System.out.println(
                "paths of file1 and file2 are same");
        }
        else {
            System.out.println(
                "Paths of file1 and file2 are not same");
        }
  
        // Path comparision
        if (file1.compareTo(file3) == 0) {
            System.out.println(
                "paths of file1 and file3 are same");
        }
        else {
            System.out.println(
                "Paths of file1 and file3 are not same");
        }
    }
}

Output:

Comparing Path of Two Files in Java

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :