$show=/label

Java 12 Files mismatch Method Example to Compare two Files

SHARE:

A quick guide to Java 12 API Files mismatch method. Explained multiple example programs with different usecases on Comparing files with Files.mismatch().

1. Java 12 Files mismatch Overview

In this post, We will learn about new method mismatch() added in Java 12 to Files class. Files class is in package java.nio.file.Files.

java.nio.file.Files class consists exclusively of static methods that operate on files, directories, or other types of files. In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Java 12 API Files mismatch


We will learn how to compare two files using Files.mismatch method.

JDK 12 introduces the new way to determine equality between two files.


2. Files mismatch() Method

2.1 Description

Finds and returns the position of the first mismatched byte in the content of two files, or -1L if there is no mismatch. The position will be in the inclusive range of 0L up to the size (in bytes) of the smaller file.

2.2  Syntax


public static long mismatch​(Path path, Path path2) throws IOException

2.3 Parameters


    path - the path to the first file
    path2 - the path to the second file

2.4 Returns

The position of the first mismatch or -1L if no mismatch

2.5 Conditions


Two files are considered to match if they satisfy one of the following conditions:

    The two paths locate the same file, even if two equal paths locate a file does not exist, or
    The two files are the same size, and every byte in the first file is identical to the corresponding byte in the second file.

Otherwise there is a mismatch between the two files and the value returned by this method is:

    The position of the first mismatched byte, or
    The size of the smaller file (in bytes) when the files are different sizes and every byte of the smaller file is identical to the corresponding byte of the larger file.

2.6 Exceptions to be thrown


IOException - if an I/O error occurs
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to both files.

3. Files mismatch() Method Example


This method is used to compare two files content. We will test this method with different scenarios as below.

3.1 Files with same content


Here taking two files file1.txt and file2.txt. Taken content in both files is "first line".

file1.txt content:

first line

file2.txt content:

first line

mismatch method takes two files path and compares the content char by char. If same returns -l otherwise returns first position of mismatch. See the below example how to use mismatch method.

package examples.java.w3schools.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MismatchExample {

 public static void main(String[] args) {
  Path path1 = Paths
    .get("C:\\Demo-Java-12\\file1.txt");
  Path path2 = Paths
    .get("C:\\Demo-Java-12\\file2.txt");

  try {
   long diff = Files.mismatch(path1, path2);

   if (diff == -1L) {
    System.out.println("file1.txt and file2.txt files are having identical content");
   } else {
    System.out.println("file1.txt and file2.txt are non identical");
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Output:

The above program compiles and run successfully in Java 12 version and produces this output.

file1.txt and file2.txt files are having identical content

3.2 Files with Non-Identical Content


We will take two temp files which are having different content as in below example.

package examples.java.w3schools.java12.files;

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

public class MismatchExampleSameContent {

 public static void main(String[] args) {
  try {
   Path filePath1 = Files.createTempFile("my-file", ".txt");
   Path filePath2 = Files.createTempFile("my-file2", ".txt");
   Files.writeString(filePath1, "This is a text file 1");
   Files.writeString(filePath2, "This is a text file 2 for testing");

   long diff = Files.mismatch(filePath1, filePath2);

   System.out.println("file1.txt and file2.txt are non identical");
   System.out.println("Found different character at index: " + diff);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Output:

file1.txt and file2.txt are non identical
Found different character at index: 20

3.3 Passing same file names to path1 and path2

We will be passing the files as below. path1 is passed to First and second parameter.

package examples.java.w3schools.java12.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MismatchExampleSameFile {

 public static void main(String[] args) {
  Path path1 = Paths
    .get("C:\\Demo-Java-12\\file1.txt");
  Path path2 = Paths
    .get("C:\\Demo-Java-12\\file2.txt");

  try {
   long diff = Files.mismatch(path1, path1);
   System.out.println("file1.txt and file2.txt files are having identical content");
   System.out.println("Files are same and no diff character found because returned " + diff);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Output:

file1.txt and file2.txt files are having identical content
Files are same and no diff character found because returned -1

JDK 12 Early Access Build 20

4. Conclusion


In this article, We've seen what is new method added in java 12 Files API. How to compare two files content using Files mismatch() method.

Next, written exmaple programs on if two files are having identical and non indentical contents.

Finally, Implemented if two file location are same then what output will be produces.

All the program shown in this article are on GitHub.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 12 Files mismatch Method Example to Compare two Files
Java 12 Files mismatch Method Example to Compare two Files
A quick guide to Java 12 API Files mismatch method. Explained multiple example programs with different usecases on Comparing files with Files.mismatch().
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi33HSstCyam65g5P8zY7ivJjgz3NprwXuSk2hbZMvHOtYo_-QNcWKwBj42uOFaQed_aDnlM7UJgE8YE_gqrpo_olal6XOZu6CGusSwnhgEBYY5vJez9QVWkdCdDYvZVN8SBmmTKVpY3UA/s320/Java+12+API+Files+mismatch.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi33HSstCyam65g5P8zY7ivJjgz3NprwXuSk2hbZMvHOtYo_-QNcWKwBj42uOFaQed_aDnlM7UJgE8YE_gqrpo_olal6XOZu6CGusSwnhgEBYY5vJez9QVWkdCdDYvZVN8SBmmTKVpY3UA/s72-c/Java+12+API+Files+mismatch.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/04/files.mismatch.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/04/files.mismatch.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content