Java contentEquals(final File file1, final File file2) Utility Method

Java contentEquals(final File file1, final File file2) Utility Method - Compares the contents of two files to determine if they are equal or not.

Java contentEquals(final File file1, final File file2) Utility Method - Compares the contents of two files to determine if they are equal or not

/**
 * Compares the contents of two files to determine if they are equal or not.
 * <p>
 * This method checks to see if the two files are different lengths
 * or if they point to the same file, before resorting to byte-by-byte
 * comparison of the contents.
 * <p>
 * Code origin: Avalon
 *
 * @param file1 the first file
 * @param file2 the second file
 * @return true if the content of the files are equal or they both don't
 * exist, false otherwise
 * @throws IOException in case of an I/O error
 */
public static boolean contentEquals(final File file1, final File file2) throws IOException {
    final boolean file1Exists = file1.exists();
    if (file1Exists != file2.exists()) {
        return false;
    }

    if (!file1Exists) {
        // two not existing files are equal
        return true;
    }

    if (file1.isDirectory() || file2.isDirectory()) {
        // don't want to compare directory contents
        throw new IOException("Can't compare directories, only files");
    }

    if (file1.length() != file2.length()) {
        // lengths differ, cannot be equal
        return false;
    }

    if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
        // same file
        return true;
    }

    try (InputStream input1 = new FileInputStream(file1); InputStream input2 = new FileInputStream(file2)) {
        return IOUtils.contentEquals(input1, input2);
    }
}

Comments