Home »
Java programming language
Java File Class int compareTo(File filepath) method with Example
Java File Class int compareTo(File filepath) method: Here, we are going to learn about the int compareTo(File filepath) method of File class with its syntax and example.
Submitted by Preeti Jain, on July 14, 2019
File Class int compareTo(File filepath)
- This method is available in package java.io.File.compareTo(File obj).
- This method is used to compare two filepath or files whether they are lexicographically equal or not.
- The return type is int that means if it returns 0 then both files are equal if it returns negative value then the first argument will be less than the given argument and if it returns greater than 0 then the first argument will be greater than 0.
Syntax:
int compareTo(File filepath){
}
Parameter(s):
We pass only one object as a parameter in the method of the File i.e filepath. This argument will be compared with other arguments.
Return value:
The return type of this method is int. So, it returns integer value(0, greater than 0, or less than 0).
Java program to demonstrate example of compareTo() method
// import the File class because we will use File class methods
import java.io.File;
// import the Exception class because it may raise
// an exception when working with files
import java.lang.Exception;
public class CompareFile {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
int compare;
// creating two file object with absolute path
File file1 = new File("E:\\Programs\\myjava.txt");
File file2 = new File("E:\\Programs\\myjava1.txt");
// By using compareTo(file2) this method will return
// negative integer because file1 length will be less
// than the file2
compare = file1.compareTo(file2);
if (compare == 0)
System.out.println("Both files are equal");
if (compare < 0)
System.out.println("file1 is less than file2");
if (compare > 0)
System.out.println("file1 is greater than file2");
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
E:\Programs>javac CompareFile.java
E:\Programs>java CompareFile
file1 is less than file2