Java 12 – File mismatch method

  • Post author:
  • Post category:Java 12
  • Post comments:1 Comment
Java 12 - File mismatch method

This topic is about 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

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

ApiTester.java

import java.io.IOException;
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, "Adglob");
      Files.writeString(path2, "Adglob");

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

      System.out.println();

      Path path3 = Files.createTempFile("file3", ".txt");
      Files.writeString(path3, "Adglob 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");
      }

      path1.toFile().deleteOnExit();
      path2.toFile().deleteOnExit();
      path3.toFile().deleteOnExit();
   }
}

Output

Files matched

Mismatch occurred in file1 and file3 at : 14

In this topic we learned about Java 12 – File mismatch method. To know more, Click Here.

This Post Has One Comment

Leave a Reply