Java 12 文件不匹配方法

来源:这里教程网 时间:2026-02-17 21:24:08 作者:

Java 12 文件不匹配方法

Java 12引入了一种通过以下语法比较两个文件的简便方法−

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

在没有不匹配的情况下,返回1L;否则返回第一个不匹配的位置。

如果文件大小不匹配或字节内容不匹配,则会考虑不匹配。

考虑以下示例-

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, "tutorialspoint");      Files.writeString(path2, "tutorialspoint");      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, "tutorialspoint 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();   }}

输出

Files matchedMismatch occurred in file1 and file3 at : 14

相关推荐