Java如何比较两个任意文件是否相同

 更新时间:2024年04月20日 16:43:59   作者:JFS_Study  
这篇文章主要为大家详细介绍了Java如何实现比较两个任意文件是否相同,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下

一、比较规则

  • 先比较两个文件的长度,如果不一样则文件肯定不一样。
  • 否则将文件读取出来,一个字节一个字节的比较二者内容是否相同。
public class FileCompare {
    public static void main(String[] args) {
        System.out.println("请依次输入两个文件的全路径和文件名:");
        System.out.println("firstFile:");
        String firstFile = inputFileName();
        System.out.println("secondFile:");
        String secondFile = inputFileName();
        System.out.println("Start to compare ...");
        FileCompare fileCompare = new FileCompare();
        fileCompare.compareFile(firstFile, secondFile);
    }

    private static String inputFileName() {
        BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
        String fileName = null;
        try {
            fileName = buffRead.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private void compareFile(String firFile, String secFile) {
        try {
            BufferedInputStream fir = new BufferedInputStream(new FileInputStream(firFile));
            BufferedInputStream sec = new BufferedInputStream(new FileInputStream(secFile));
            //比较文件的长度是否一样
            if (fir.available() == sec.available()) {
                while (true) {
                    int firRead = fir.read();
                    int secRead = sec.read();
                    if (firRead == -1 || secRead == -1) {
                        System.out.println("two files are same!");
                        break;
                    } else if (firRead != secRead) {
                        System.out.println("Files not same!");
                        break;
                    }
                }
            } else {
                System.out.println("two files are different!");
            }
            fir.close();
            sec.close();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

二、File 中的 length() 与IO中 InputStream 类中的 available()

1️⃣File 中的 length() 返回 long,表示文件的大小。

2️⃣IO 中 InputStream 类中的 available() 返回 int。表示该 inputstream 在不被阻塞的情况下一次可以读取到的数据长度。

三、方法补充

除了上文的方法,小编还为大家整理了其他Java比较文件的方法,希望对大家有所帮助

java实现两个文件对比

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class check {
    public static void main(String[] args) {
        Set<String> allStuNames = new HashSet<>();

        try {
            FileReader fileReader = new FileReader("name.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 逐行处理文本内容
//                System.out.println(line);
                allStuNames.add(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        System.out.println(allStuNames);

        List<String> lst = new ArrayList<>();

        try {
            FileReader fileReader = new FileReader("a.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 逐行处理文本内容
//                System.out.println(line);
                lst.add(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(String desc : lst){
            for(String name : allStuNames){
                if(desc.contains(name)){
                    System.out.println(name);
                    System.out.println(desc);
                }
            }
        }
    }
}

利用md5判断两个文件是否相同

例子:

根据不同路径下两个文件来判断:

package com.letv.test;
 
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
 
public class CheckSameFile {
	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
 
	public static void main(String[] args) {
		String path1 = "d:/test/abc.jpg";
		String path2 = "d:/test/asd/abc.jpg";
 
		String hash_path1 = null;
		String hash_path2 = null;
		try {
			hash_path1 = getHash(path1, "MD5");
			hash_path2 = getHash(path2, "MD5");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("path1 md5:" + hash_path1);
		System.out.println("path2 md5:" + hash_path2);
		if (hash_path1.endsWith(hash_path2)) {
			System.out.println("文件相同");
		} else {
			System.out.println("文件不相同");
		}
	}
 
	/**
	 * 获得文件md5值
	 */
	public static String getHash(String fileName, String hashType)
			throws Exception {
		InputStream fis;
		fis = new FileInputStream(fileName);
		byte[] buffer = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead = 0;
		while ((numRead = fis.read(buffer)) > 0) {
			md5.update(buffer, 0, numRead);
		}
		fis.close();
		return toHexString(md5.digest());
	}
 
	/**
	 * md5转成字符串
	 */
	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}

通过比较文件每一个字节判断

	public static boolean isSameFile(String filePath1, String filePath2) {
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;

        try {
            fis1 = new FileInputStream(filePath1);
            fis2 = new FileInputStream(filePath2);

            // 获取文件的总字节数
            int len1 = fis1.available();
            int len2 = fis2.available();

            // 判断两个文件的字节长度是否一样,长度相同则比较具体内容
            if (len1 == len2) {
                // 建立字节缓冲区
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];

                // 将文件写入缓冲区
                fis1.read(data1);
                fis2.read(data2);

                // 依次比较文件中的每个字节
                for (int i = 0; i < len1; i++) {
                    if (data1[i] != data2[i]) {
                        System.out.println("文件内容不一样");
                        return false;
                    }
                }
                System.out.println("文件内容相同");
                return true;
            } else {
                // 文件长度不一样,内容肯定不同
                System.out.println("文件内容不同");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭资源
            if (fis1!=null){
                try {
                    fis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis2!=null){
                try {
                    fis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

使用缓冲流比较,在比较大文件时效率相比普通流效率高

    public static boolean isSameFile2(String filePath1, String filePath2) {
        BufferedInputStream bis1 = null;
        BufferedInputStream bis2 = null;
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;

        try {
            // 获取文件输入流
            fis1 = new FileInputStream(filePath1);
            fis2 = new FileInputStream(filePath2);
            // 将文件输入流包装成缓冲流
            bis1 = new BufferedInputStream(fis1);
            bis2 = new BufferedInputStream(fis2);

            // 获取文件字节总数
            int len1 = bis1.available();
            int len2 = bis2.available();

            // 判断两个文件的字节长度是否一样,长度相同则比较具体内容
            if (len1 == len2) {
                // 建立字节缓冲区
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];

                // 将文件写入缓冲区
                bis1.read(data1);
                bis2.read(data2);
                // 依次比较文件中的每个字节
                for (int i = 0; i < len1; i++) {
                    if (data1[i] != data2[i]) {
                        System.out.println("文件内容不一致");
                        return false;
                    }
                }
                System.out.println("文件内容一致");
                return true;
            } else {
                System.out.println("文件长度不一致,内容不一致");
                return false;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis1 != null) {
                try {
                    bis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis2 != null) {
                try {
                    bis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis1 != null) {
                try {
                    fis1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis2 != null) {
                try {
                    fis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

将文件分多次读入,然后通过MessageDigest进行MD5加密,最后再通过BigInteger类提供的方法进行16进制的转换

	/**
     * 计算文件的MD5值
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte[] buffer = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

public static void main(String[] args) throws IOException {

        String filePath1="/Users/zhouzhxu/desktop/test.csv";
        String filePath2="/Users/zhouzhxu/desktop/test2.csv";

        String fileMD51 = getFileMD5(new File(filePath1));
        String fileMD52 = getFileMD5(new File(filePath2));

        System.out.println(fileMD51);
        System.out.println(fileMD52);

    }

到此这篇关于Java如何比较两个任意文件是否相同的文章就介绍到这了,更多相关Java比较文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring解决循环依赖问题及三级缓存的作用

    Spring解决循环依赖问题及三级缓存的作用

    这篇文章主要介绍了Spring解决循环依赖问题及三级缓存的作用,所谓的三级缓存只是三个可以当作是全局变量的Map,Spring的源码中大量使用了这种先将数据放入容器中等使用结束再销毁的代码风格
    2022-07-07
  • Java数组(Array)最全汇总(下篇)

    Java数组(Array)最全汇总(下篇)

    这篇文章主要介绍了Java数组(Array)最全汇总(下篇),本文章内容详细,通过案例可以更好的理解数组的相关知识,本模块分为了三部分,本次为下篇,需要的朋友可以参考下
    2023-01-01
  • JPA save()方法将字段更新为null的解决方案

    JPA save()方法将字段更新为null的解决方案

    这篇文章主要介绍了JPA save()方法将字段更新为null的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • java爬虫Gecco工具抓取新闻实例

    java爬虫Gecco工具抓取新闻实例

    本篇文章主要介绍了JAVA 爬虫Gecco工具抓取新闻实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2016-10-10
  • shiro整合swagger的注意事项

    shiro整合swagger的注意事项

    这篇文章主要介绍了shiro整合swagger需要注意的地方,帮助大家更好的理解和学习使用shiro框架,感兴趣的朋友可以了解下
    2021-05-05
  • Java 数据库连接池 DBCP 的介绍

    Java 数据库连接池 DBCP 的介绍

    这篇文章主要给大家分享的是 Java 数据库连接池 DBCP 的介绍, 是 Apache 旗下 Commons 项目下的一个子项目,提供连接池功能DBCP,下面来看看文章的具体介绍内容吧,需要的朋友可以参考一下
    2021-11-11
  • JAVA线程池原理实例详解

    JAVA线程池原理实例详解

    这篇文章主要介绍了JAVA线程池原理,结合实例形式详细分析了java线程池概念、原理、创建、使用方法及相关注意事项,需要的朋友可以参考下
    2019-03-03
  • Java中Redis的布隆过滤器详解

    Java中Redis的布隆过滤器详解

    这篇文章主要介绍了Java中Redis的布隆过滤器详解,我们经常会把一部分数据放在Redis等缓存,比如产品详情,这样有查询请求进来,我们可以根据产品Id直接去缓存中取数据,而不用读取数据库,这是提升性能最简单,最普遍,也是最有效的做法,需要的朋友可以参考下
    2023-09-09
  • 关于Idea清除缓存并重启解决的问题

    关于Idea清除缓存并重启解决的问题

    这篇文章主要介绍了关于Idea清除缓存并重启解决的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-09-09
  • MyBatis注解开发之实现自定义映射关系和关联查询

    MyBatis注解开发之实现自定义映射关系和关联查询

    本文主要详细介绍了MyBatis注解开发中,实现自定义映射关系和关联查询,文中有详细的代码示例,对学习MyBatis有一定的参考价值,需要的朋友可以参考阅读
    2023-04-04

最新评论