-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathfiles-mismatch.yaml
More file actions
47 lines (47 loc) · 1.53 KB
/
files-mismatch.yaml
File metadata and controls
47 lines (47 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
---
id: 62
slug: "files-mismatch"
title: "Files.mismatch()"
category: "io"
difficulty: "beginner"
jdkVersion: "12"
oldLabel: "Java 8"
modernLabel: "Java 12+"
oldApproach: "Manual Byte Compare"
modernApproach: "Files.mismatch()"
oldCode: |-
// 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
modernCode: |-
long pos = Files.mismatch(path1, path2);
// -1 if identical
// otherwise: position of first difference
summary: "Compare two files efficiently without loading them into memory."
explanation: "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."
whyModernWins:
- icon: "⚡"
title: "Memory-efficient"
desc: "Doesn't load entire files into byte arrays."
- icon: "🎯"
title: "Pinpoints difference"
desc: "Returns the exact byte position of the first mismatch."
- icon: "📏"
title: "One call"
desc: "No manual byte array comparison logic."
support:
state: "available"
description: "Widely available since JDK 12 (March 2019)"
prev: "io/file-memory-mapping"
next: "io/deserialization-filters"
related:
- "io/inputstream-transferto"
- "io/deserialization-filters"
- "io/writing-files"
docs:
- title: "Files.mismatch()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Files.html#mismatch(java.nio.file.Path,java.nio.file.Path)"