Open In App

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:




// 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 comparison
        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 comparison
        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:


Article Tags :