Best Way To Compare Two Text File In Java


For comparing two text files best way is to compare them line by line or we can do this by computing and comparing MD5 checksum of both files. For comparing text file line by line the FileUtils class of Apache Commons IO Java library is best option as it has all checks and well tested code.

Library Information

Platform information

jdk1.8.0_60, Java 8, Eclipse

Used library Name: Commons IO

Maven Dependency Entry

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

Gradle Dependency Entry

compile \'commons-io:commons-io:2.4\'

Jar Download Location: Download Jar

Methods used: FileUtils provides method contentEqualsIgnoreEOL to compare two text files line by line. This method checks to see if the two files point to the same file, before resorting to line-by-line comparison of the contents. These methods have all required checks and exception handling. For any production grade Java application it is good to use this utility as it will save effort.

public static boolean contentEqualsIgnoreEOL(File file1,
       File file2, String charsetName) throws IOException
Example
package org.code4copy;

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

import org.apache.commons.io.FileUtils;

public class CompareTwoTextFiles {

    public static void main(String[] args) throws IOException {
        File f1 = new File("C:\\example\\1.txt");
        File f2 = new File("C:\\example\\2.txt");
        boolean result = FileUtils.contentEqualsIgnoreEOL(f1, f2, "utf-8");
        if(!result){
            System.out.println("Files content are not equal.");
        }else{
            System.out.println("Files content are equal.");
        }
        
        result = FileUtils.contentEqualsIgnoreEOL(f1, f1, "utf-8");
        if(!result){
            System.out.println("Files content are not equal.");
        }else{
            System.out.println("Files content are equal.");
        }
    }

}

Output

Files content are not equal.
Files content are equal.

Download code from here


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.