In this post under Apache Commons IO, I will show with example the easiest way to compare whether contents of two files are equal or not.
Apache Commons “IOUtils” class provide a static method called “contentEquals” which compare contents of two file and return a boolen.
Below is the complete main code
Main class
package ioutils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Example2 {
public static void main(String[] args) throws IOException {
File file1 = new File("Quotes1.txt");
File file2 = new File("Quotes2.txt");
File file3 = new File("Quotes3.txt");
try(FileReader fileReader1 = new FileReader(file1);
FileReader fileReader2 = new FileReader(file2);
FileReader fileReader3 = new FileReader(file3)) {
boolean equals = IOUtils.contentEquals(fileReader1, fileReader2);
System.out.println("Quotes1 equals Quotes2: " + equals);
equals = IOUtils.contentEquals(fileReader2, fileReader3);
System.out.println("Quotes2 equals Quotes3: " + equals);
}
}
}
In the above code at line 11, 12, 13 I create three “File” instances one for “Quotes1.txt” file, second for “Quotes2.txt”, and third for “Quotes3.txt” file.
In the try-with-resource block, I create three “FileReader” instances one for each “File” instances.
At line 17, I call “contentEquals” method of “IOUtils” class and pass two instances of “FileReader” class as method argument.
The “contentEquals” method will compare the contents of the two file and return a boolean value.
In this way we can check whether contents of two files are equal or not.