How do I use Files.mismatch() to compare files?

In Java, java.nio.file.Files.mismatch(Path, Path) is a powerful method introduced in Java 12 that allows you to compare the contents of two files efficiently. It returns the position of the first byte where the two files differ, or -1L if they are identical.

How to use Files.mismatch

Here is a basic example of how to implement it:

package org.kodejava.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileCompare {
    public static void main(String[] args) {
        Path path1 = Path.of("file1.txt");
        Path path2 = Path.of("file2.txt");

        try {
            long mismatch = Files.mismatch(path1, path2);

            if (mismatch == -1L) {
                System.out.println("Files are identical.");
            } else {
                System.out.println("Files differ at byte position: " + mismatch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Key Behaviors to Keep in Mind:

  1. Return Values:
    • -1L: The files are identical (same size and same content).
    • A non-negative value: The index of the first byte that differs.
    • File Size Mismatch: If one file is a prefix of the other, it returns the size of the smaller file as the mismatch point.
  2. Performance: Files.mismatch is generally faster than manual byte-by-byte comparison because it uses optimized internal buffers.
  3. Same Path: If you pass the exact same Path object (or two paths that point to the same file via Files.isSameFile), it returns -1L immediately without reading the content.
  4. Exceptions: It throws an IOException if there’s an error reading the files or if one of the paths does not exist.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.