Tuesday, 25 August 2015

Check contents of two files are equal or not in Java

Some times you need to check whether content of two files is equal or not. Following are some of the ways to check, whether contents of files are equal or not.

Using Apache commons io library
'org.apache.commons.io.FileUtils' class provide contentEquals method to check whether two files has same content or not.
import java.io.File;

import org.apache.commons.io.FileUtils;

public class FileUtilities {
 public static boolean isFilesEqual(String file1, String file2) {
  try {
   return FileUtils.contentEquals(new File(file1), new File(file2));
  } catch (Exception e) {
   return false;
  }
 }

 public static void main(String args[]) {
  String file1 = "/Users/harikrishna_gurram/sample.txt";
  String file2 = "/Users/harikrishna_gurram/sample1.txt";
  String file3 = "/Users/harikrishna_gurram/sample2.txt";

  System.out.println(isFilesEqual(file1, file2));
  System.out.println(isFilesEqual(file1, file3));
  System.out.println(isFilesEqual(file2, file3));
 }
}

Using java.nio.file.Files class
If you don’t want to use external libraries, from java7 onwards, you can convert file content to byte array. Once you convert data to array format, you can check whether arrays are equal or not using ‘Arrays.equals’ method.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileUtilities {
 public static boolean isFilesEqual(String file1, String file2) {
  try {
   byte[] f1 = Files.readAllBytes(Paths.get(file1));
   byte[] f2 = Files.readAllBytes(Paths.get(file2));
   return Arrays.equals(f1, f2);
  } catch (Exception e) {
   return false;
  }

 }

 public static void main(String args[]) {
  String file1 = "/Users/harikrishna_gurram/sample.txt";
  String file2 = "/Users/harikrishna_gurram/sample1.txt";
  String file3 = "/Users/harikrishna_gurram/sample2.txt";

  System.out.println(isFilesEqual(file1, file2));
  System.out.println(isFilesEqual(file1, file3));
  System.out.println(isFilesEqual(file2, file3));
 }
}

By calculating hash values for files
Calculate hash values for contents of two files. If hash values are same, then both files has same content, else not.

Following post explains, how to compute hash value for given file.





No comments:

Post a Comment