Comparing Path of Two Files in Java

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Comparing Path of Two Files in Java

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.