Compare two files efficiently without loading them into memory.
Porównanie kodu
✕ Java 8
// Compare two files byte by byte byte[] f1 = Files.readAllBytes(path1); byte[] f2 = Files.readAllBytes(path2); boolean equal = Arrays.equals(f1, f2); // loads both files entirely into memory
✓ Java 12+
long pos = Files.mismatch(path1, path2); // -1 if identical // otherwise: position of first difference
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Memory-efficient
Doesn't load entire files into byte arrays.
Pinpoints difference
Returns the exact byte position of the first mismatch.
One call
No manual byte array comparison logic.
Stare podejście
Manual Byte Compare
Nowoczesne podejście
Files.mismatch()
Od JDK
12
Poziom trudności
Początkujący
Wsparcie JDK
Files.mismatch()
Dostępne
Widely available since JDK 12 (March 2019)
Jak to działa
Files.mismatch() returns the position of the first byte that differs, or -1 if the files are identical. It reads lazily and short-circuits on the first difference.
Powiązana dokumentacja