Files Mismatch Compare File Bytes
Compare two files byte by byte with Files.mismatch: identical content yields -1, otherwise you get the offset of the first divergent byte, no manual loops.
Code
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class BuildArtifactCheck {
public static void main(String[] args) throws IOException {
Path left = Files.createTempFile("left-", ".txt");
Path right = Files.createTempFile("right-", ".txt");
Files.writeString(left, "sha256:aa11\nsize:1024\n", StandardCharsets.UTF_8);
Files.writeString(right, "sha256:aa11\nsize:1024\n", StandardCharsets.UTF_8);
// 逐字节比较(byte compare):完全相同返回 -1
System.out.println("identical files: " + Files.mismatch(left, right));
Files.writeString(right, "sha256:bb22\nsize:1024\n", StandardCharsets.UTF_8);
// 内容不同时返回第一个不同字节的偏移(0 起)
System.out.println("first diff at: " + Files.mismatch(left, right));
Files.deleteIfExists(left);
Files.deleteIfExists(right);
}
}How the snippet works
Files Mismatch Compare File Bytes keeps everything in the class BuildArtifactCheck.
Applying it
Running the file prints labeled results such as identical files:, first diff at: — each operation’s effect is visible in the output.
Statements that matter
Files.writeString(right, "sha256:aa11\nsize:1024\n", StandardCharsets.UTF_8);
Files.writeString(right, "sha256:bb22\nsize:1024\n", StandardCharsets.UTF_8);
Files.writeString(left, "sha256:aa11\nsize:1024\n", StandardCharsets.UTF_8);
Interactive Tools for This Topic
Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
FAQ
- What does Files Mismatch Compare File Bytes print when run?
- Execute the whole file; each printed line is prefixed with a label like `identical files:`, `first diff at:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.