View ToC

Java 12 - File mismatch method

Java 12 introduces an easy way to compare two files using following syntax −

public static long mismatch(Path path1, Path path2) throws IOException


  • 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 example −

import java.nio.file.Files;
import java.nio.file.Path;

public class APITester {
   public static void main(String[] args) throws IOException {
      Path path1 = Files.createTempFile("file1", ".txt");
      Path path2 = Files.createTempFile("file2", ".txt");

      Files.writeString(path1, "tutorialsforgeeks");
      Files.writeString(path2, "tutorialsforgeeks");

      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");


      Path path3 = Files.createTempFile("file3", ".txt");
      Files.writeString(path3, "tutorialsforgeeks Java 12");

      mismatch = Files.mismatch(path1, path3);

      if(mismatch > 1L) {
         System.out.println("Mismatch occurred in file1 and file3 at : " + mismatch);
      }else {
         System.out.println("Files matched");



Files matched

Mismatch occurred in file1 and file3 at : 14