Pages Navigation Menu

Coding is much easier than you think

Compare two files by content in Java

In this tutorial, we will provide a simplified approach to compare two files in Java by content. We will use Apache Commons IO library to perform this comparison, and run this against some test files we prepare to see the results.
 

 
Before start download commons-io-2.4.jar  and add in your classpath.
 
We will use the contentEquals() method of the FileUtils class of the above library to compare the file content.
 
The Java program to compare two files by content using Apache Commons IO, is provided below:
 

package com.simplecode.jdbc;

import java.io.File;
import org.apache.commons.io.FileUtils;

public class compareFileContent
{
	public static void main(String[] args) throws Exception
	{
		/* Get the files to be compared first */
		File file1 = new File(args[0]);
		File file2 = new File(args[1]);
	
		boolean compareResult = FileUtils.contentEquals(file1, file2);
		System.out.println("Are the files are same? " + compareResult);
		
	}
}

 

Using this code we can compare any two files (text , image , pdf etc)

Recommended Article

 
The comparison works because, it is done as a byte by byte comparison between the two files as per the API docs. You can compare any two files using this code, be it of any format. One drawback of this approach, is that if one of the files has additional metadata but same content, the comparison still returns false. This is acceptable in one angle and otherwise. So, you may want to make use of this approach depending on your requirement.