Java 12 introduces an easy way to compare two files using following syntax −
public static long mismatch(Path path1, Path path2) throws IOException
Where
- If there is no mismatch then 1L is returned else position of first mismatch is returned.
- Mismatch is accounted in case if file sizes are not matching or byte contents are not matching.
Consider the following program −
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Java12FileMismatch {
public static void main(String[] args) throws IOException {
// 1. Check file1 and file2 are matching
Path path1 = Files.createTempFile("file1", ".txt");
Path path2 = Files.createTempFile("file2", ".txt");
Files.writeString(path1, "Hi Techpoints");
Files.writeString(path2, "Hi Techpoints");
checkFileMismatch(path1, path2);
// 2. Check file1 and file3 are matching
Path path3 = Files.createTempFile("file3", ".txt");
Files.writeString(path3, "Hi Techpoints Java 12");
checkFileMismatch(path1, path3);
path1.toFile().deleteOnExit();
path2.toFile().deleteOnExit();
path3.toFile().deleteOnExit();
}
private static void checkFileMismatch(Path path1, Path path2) throws IOException {
long mismatch = Files.mismatch(path1, path2);
if (mismatch > 1L) {
System.out.println("Mismatch occurred in file1 and file2 at : " + mismatch);
} else {
System.out.println("Files matched");
}
}
}
Output:
Now run the Java8DateTime as follows −
C:\hitechpoints\workspace\java12-feature\src>java Java12FileMismatch.java
It should produce the following output −
Files matched
Mismatch occurred in file1 and file2 at : 13