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:
- 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.
- Performance:
Files.mismatchis generally faster than manual byte-by-byte comparison because it uses optimized internal buffers. - Same Path: If you pass the exact same
Pathobject (or two paths that point to the same file viaFiles.isSameFile), it returns-1Limmediately without reading the content. - Exceptions: It throws an
IOExceptionif there’s an error reading the files or if one of the paths does not exist.
