What's a quick way to tell if the contents of two files are identical or not?
Author: Deron Eriksson
Description: This Java tutorial describes a quick way to compare the contents of two files using Commons IO.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The contentEquals() method of the FileUtils class of the ApacheSW Commons IOS library is useful for comparing the contents of two files to determine whether the contents are identical or not. This is demonstrated in the CompareFileContents class.

CompareFileContents.java

package test;

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

import org.apache.commons.io.FileUtils;

public class CompareFileContents {

	public static void main(String[] args) throws IOException {

		File file1 = new File("test1.txt");
		File file2 = new File("test2.txt");
		File file3 = new File("test3.txt");

		boolean compare1and2 = FileUtils.contentEquals(file1, file2);
		boolean compare2and3 = FileUtils.contentEquals(file2, file3);
		boolean compare1and3 = FileUtils.contentEquals(file1, file3);

		System.out.println("Are test1.txt and test2.txt the same? " + compare1and2);
		System.out.println("Are test2.txt and test3.txt the same? " + compare2and3);
		System.out.println("Are test1.txt and test3.txt the same? " + compare1and3);

	}

}

The CompareFileContents class compares 3 files: test1.txt, test2.txt, and test3.txt. The first and second files have identical contents while the third file has different contents.

test1.txt

1 and 2 are the same

test2.txt

1 and 2 are the same

test3.txt

3 is different

The execution of CompareFileContents is shown below. The test1.txt and test2.txt files have identical contents while test3.txt is different from test1.txt and test2.txt.

Results

Are test1.txt and test2.txt the same? true
Are test2.txt and test3.txt the same? false
Are test1.txt and test3.txt the same? false