Friday, May 4, 2012

Comparing two files with any extenstion in java


You can use following code to compare any two files with any extenstion.


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

public class FileComparatorImpl {

      public boolean compare(String pathA, String pathB) {
            File fileA = new File(pathA);
            File fileB = new File(pathB);
            return compare(fileA, fileB);
      }

      public boolean compare(File fileA, File fileB) {
            if (fileA == null && fileB == null) {
                  return true;
            }
            if (fileA == null) {
                  return false;
            }
            if (fileB == null) {
                  return false;
            }
            if (fileA == fileB) {
                  return true;
            }
            if (fileA.equals(fileB)) {
                  return true;
            }
            boolean isFileA = fileA.isFile();
            boolean isFileB = fileB.isFile();

            if (isFileA != isFileB) {
               return false;
            }
            if (!isFileA) {
             throw new RuntimeException("These are not files.");
            }
            if (isFileA && isFileB) {
                  BufferedInputStream bisA = null;
                  BufferedInputStream bisB = null;
                  try {
                        bisA = new BufferedInputStream(
                                   new FileInputStream(fileA));
                        bisB = new BufferedInputStream(
                                  new FileInputStream(fileB));
                        while (true) {
                              int readA = bisA.read();
                              int readB = bisB.read();
                              if (readA != readB) {
                                    return false;
                              }
                              if (readA == -1) {
                                    return true;
                              }
                        }
                  } catch (Exception e) {
                        throw new RuntimeException(
                              "Failed to read the files.");
                  } finally {
                        try {
                              if (bisA != null) {
                                    bisA.close();
                              }
                              if (bisB != null) {
                                    bisB.close();
                              }
                        } catch (Exception e) {
                        }
                  }
            }
            return false;
      }
}

No comments:

Post a Comment