Java12 introduced a mismatch method to java.nio.file.Files
Class.
Mismatch compares two files and returns the position of the matched first content byte of a file. If there is no match, Returns -1.
Here is an example.
public static long mismatch(Path path, Path path2) throws IOException
The below use case return -1 and If two files are matched,
- if both files are referring to the same file and location
- original and copied files
- same content in different files in different locations
- two-path files of the same size and content is the same
- soft and hard-linked files of the same content
Below are mismatched cases and return long number.
- First occurrence of mismatched content
- The small size files’ mismatched position is returned
Here is an example
package java12;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FilesMisMatch {
public static void main(String[] args) {
//Path object with given file in File System
Path path1= Paths.get("a:\\", "test1.txt");
Path path2= Paths.get("a:\\", "test2.txt");
Path path3= Paths.get("a:\\", "test3.txt");
try {
Files.writeString(path1, "Test content inserted into a file", StandardOpenOption.CREATE);
Files.writeString(path2, "Test content inserted into a file", StandardOpenOption.CREATE);
Files.writeString(path3, "Test content inserted into a file 1", StandardOpenOption.CREATE);
long result = Files.mismatch(path1, path2);
System.out.println("Compare path1 and path2 = " + result); // returns -1
result = Files.mismatch(path2, path3);
System.out.println("Compare path2 and path3 = " + result); // returns 33
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Compare path1 and path2 = -1
Compare path2 and path3 = 33