Comparing Path of Two Files in Java

The path of two files can be compared lexicographically in Java using 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.







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



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 or mail your article to 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 to report any issue with the above content.