HOWTO · Java
How to Compare Content of Two Files in Java
This tutorial demonstrates how to compare the content of two files in Java.
On this page
Java offers several ways to compare files, depending on whether you need exact byte equality, equal text lines, or the location of the first differing byte. Use a streaming comparison for large files, line comparison when decoded line values matter (the line terminators are ignored), Files.mismatch() when it is available in your runtime, Apache Commons IO when the project already uses that dependency, or Arrays.equals() for files that comfortably fit in memory.
Choose a File-Comparison Method
| Approach | Compares | Useful when |
|---|---|---|
| Byte by byte | Every byte, including encoding and line-ending bytes | Exact content equality is required and files may be large |
| Line by line | Decoded line values, without line terminators | Text should match by line rather than by its stored bytes |
Files.mismatch() |
Bytes and the first differing byte position | The runtime provides this API and the mismatch location is useful |
| Apache Commons IO | File contents through FileUtils.contentEquals() |
The project already includes Commons IO |
Arrays.equals() |
Two complete byte arrays | Both files are small enough to load into memory |
A byte comparison treats different encodings and different line-ending sequences as different content. A line comparison decodes characters and readLine() removes line terminators, so files with the same line values can compare equal even when one uses LF and the other CRLF. It also does not distinguish a final line terminator from no final terminator. Choose based on what “same” means for your application.
Compare Files Byte by Byte in Java
Read bytes from both streams in the same loop. InputStream.read() returns a value from 0 through 255, or -1 at end of file; checking both values detects a length difference as well as a differing byte. This streaming approach uses a small, fixed buffer of stream state instead of loading both files into arrays.
Run this example:
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class Main {
static boolean equalByByte(Path first, Path second) throws IOException {
try (InputStream a = Files.newInputStream(first);
InputStream b = Files.newInputStream(second)) {
while (true) {
int x = a.read();
int y = b.read();
if (x != y) return false;
if (x == -1) return true;
}
}
}
static boolean equalByLine(Path first, Path second) throws IOException {
try (java.io.BufferedReader a = Files.newBufferedReader(first, StandardCharsets.UTF_8);
java.io.BufferedReader b = Files.newBufferedReader(second, StandardCharsets.UTF_8)) {
while (true) {
String x = a.readLine();
String y = b.readLine();
if (!java.util.Objects.equals(x, y)) return false;
if (x == null) return true;
}
}
}
static boolean equalByArrays(Path first, Path second) throws IOException {
return Arrays.equals(Files.readAllBytes(first), Files.readAllBytes(second));
}
public static void main(String[] args) throws IOException {
Path first = Files.createTempFile("first", ".txt");
Path second = Files.createTempFile("second", ".txt");
try {
Files.write(first, "DelftStack\n".getBytes(StandardCharsets.UTF_8));
Files.write(second, "DelftStack\n".getBytes(StandardCharsets.UTF_8));
System.out.println("Byte comparison: " + equalByByte(first, second));
System.out.println("Line comparison: " + equalByLine(first, second));
System.out.println("Array comparison: " + equalByArrays(first, second));
} finally {
Files.deleteIfExists(first);
Files.deleteIfExists(second);
}
}
}
Byte comparison: true
Line comparison: true
Array comparison: true
The stream comparison returns false as soon as a byte differs or one stream ends first, and returns true when both reach end of file together. Try-with-resources closes both streams even if reading fails. Files.newInputStream() and the other file operations can throw IOException, which this example allows main to propagate.
Compare Files Line by Line in Java
For text, open both files with the same explicit charset, then compare each pair of readLine() results with value equality. Objects.equals() handles both strings and null: if only one file has another line, the values differ; if both return null, both files have reached the end. Do not compare strings with ==, which checks whether two references identify the same object rather than whether their contents match.
The line method in the runnable example uses UTF-8. Select the charset that matches the files you need to read; using a different charset can change decoded values or cause decoding failures. Since readLine() discards terminators, use byte comparison instead if the precise newline bytes matter.
Compare Files with Files.mismatch() in Java
For example, long position = Files.mismatch(first, second); returns -1 when the files have identical bytes. Otherwise it returns the zero-based position of their first differing byte, including the first position after the shorter file when one is a prefix of the other. The Files.mismatch() API documentation describes this behavior. Its availability depends on the Java runtime in use, so confirm that the target runtime provides the method before choosing it.
Compare Files with Apache Commons IO in Java
Apache Commons IO provides FileUtils.contentEquals(File, File), which returns a boolean for content equality. Add the Commons IO dependency using the version and dependency-management method already established by your project; the library is not part of the Java standard library. For example, the call is FileUtils.contentEquals(first.toFile(), second.toFile()) after importing org.apache.commons.io.FileUtils.
This method can throw IOException, so handle or propagate that failure rather than treating it as an equality result. Its boolean alone does not prove that two existing files were compared: the method may return true when both paths are absent. If equality must mean that two files were actually compared, check that both inputs exist before calling it, then handle any I/O failure according to the application’s needs.
Compare Files with Arrays.equals() in Java
Files.readAllBytes() loads each complete file into memory, and Arrays.equals(byte[], byte[]) compares the resulting bytes. The helper in the example shows this standard-library approach. It is concise and appropriate when the files are known to be modest in size, but it can exhaust available memory for large inputs. For files whose size is uncertain, use the streaming approach or Files.mismatch() when the runtime supports it.
Choose line comparison for decoded text semantics, and byte comparison for exact stored content. Prefer streaming for large files, use Files.mismatch() when its runtime availability and mismatch position suit the task, and use Apache Commons IO when its dependency is already part of the project. Arrays.equals() is convenient when both complete files can safely fit in memory.