Compare Contents of Files in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Compare

In this Java tutorial we learn how to use the FileUtils class of Apache Commons IO library to compare the contents of two files to determine if they are equal or not equal.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to Compare the content of two Files

To determine the contents of two files equal or not we can use the method FileUtils.contentEquals() as the below Java program.

CompareTwoFiles1.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CompareTwoFiles1 {
    public static void main(String... args) {
        try {
            File file1 = new File("D:\\Data\\data.txt");
            File file2 = new File("D:\\Data\\data.txt");
            File file3 = new File("D:\\Data\\data1.txt");

            boolean compareResult1 = FileUtils.contentEquals(file1, file2);
            boolean compareResult2 = FileUtils.contentEquals(file1, file3);

            System.out.println("Compare Result file1 and file2: " + compareResult1);
            System.out.println("Compare Result file1 and file3: " + compareResult2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Compare Result file1 and file2: true
Compare Result file1 and file3: false

FileUtils class also provides the method FileUtils.contentEqualsIgnoreEOL() to compare file contents.

CompareTwoFiles2.java

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class CompareTwoFiles2 {
    public static void main(String... args) {
        try {
            File file1 = new File("D:\\Data\\data.txt");
            File file2 = new File("D:\\Data\\data.txt");
            File file3 = new File("D:\\Data\\data1.txt");

            boolean compareResult1 = FileUtils.contentEqualsIgnoreEOL(file1, file2, "UTF-8");
            boolean compareResult2 = FileUtils.contentEqualsIgnoreEOL(file1, file3, "UTF-8");

            System.out.println("Compare Result file1 and file2: " + compareResult1);
            System.out.println("Compare Result file1 and file3: " + compareResult2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Compare Result file1 and file2: true
Compare Result file1 and file3: false

Happy Coding 😊