Java比较两个文件是否完全相同 JavaIO ApacheCommonIO Files.mismatch RandomAccessFile BufferedReader

本文详述了Java中比较两个文件内容是否相同的各种方法,包括逐字节比较、按行比较、使用Files::mismatch、内存映射文件以及Apache Commons IO库。通过实例代码展示了如何实现文件内容的比对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:Compare the Content of Two Files in Java

1. Overview 概述

In this tutorial, we'll review different approaches to determine if the contents of two files are equal. We'll be using core Java Stream I/O libraries to read the contents of the files and implement basic comparisons.

在这篇文章中,我们将来查阅并使用几种不同的处理方式来判断两个文件的内容是否相同。首先会使用JavaIO库来读取文件内容并实现比对逻辑。

To finish, we'll review the support provided in Apache Commons I/O to check for content equality of two files.

之后,会使用外部库,Apache Commons IO库来实现比对逻辑,拭目以待吧

2. Byte by Byte Comparison 逐字节的进行比对

Let's start with a simple approach to reading the bytes from the two files to compare them sequentially.

最开始,让我们先以一种简单的方式来读取两个文件的字节内容并顺序的比较。

To speed up reading the files, we'll use BufferedInputStream. As we'll see, BufferedInputStream reads large chunks of bytes from the underlying InputStream into an internal buffer. When the client reads all the bytes in the chunk, the buffer reads another block of bytes from the stream.

为也加速文件读取过程,我们将使用 BufferedInputStream 类,正如它的名字那样,它从底层的输入流中读取一大块的字节数据到内部缓存块。当我们从缓存块中读取全部字节后,它会再从底层的输入流中再次读取一块字节数据,以此循环往复,直到全部数据读取完毕。

Obviously, using BufferedInputStream is much faster than reading one byte at a time from the underlying stream.

明显的,使用这种方式比从底层输入流中逐字节的读取方式要快的多。

Let's write a method that uses BufferedInputStreams to compare two files:

来使用 BufferedInputStream 编写代码实现两文件的比较吧,示例如下:

public static long filesCompareByByte(Path path1, Path path2) 
    throws IOException {
    // 一次性加载两个文件,并使用try-with-resources的方式确保流会被关闭
    try (BufferedInputStream fis1 = new BufferedInputStream(
        new FileInputStream(path1.toFile()));
         BufferedInputStream fis2 = new BufferedInputStream(
        new FileInputStream(path2.toFile()))) {
        // 此次读取的内容
        int ch = 0;
        // 用于记录两个文件是否相同,-1是相同,
        // 其它值是两个文件中较小的那个的字节长度,也就是不相同字节的所处位置
        //(毕竟文件长度不一致,则不相同的字节所处位置就是小文件的字节长度)
        long
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值