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比较文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实现的满天星效果实例

    java实现的满天星效果实例

    这篇文章主要介绍了java实现满天星效果的方法,涉及Java绘图的应用,非常具有实用价值,需要的朋友可以参考下
    2014-11-11
  • 浅谈java的接口和C++虚类的相同和不同之处

    浅谈java的接口和C++虚类的相同和不同之处

    下面小编就为大家带来一篇浅谈java的接口和C++虚类的相同和不同之处。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,祝大家游戏愉快哦
    2016-12-12
  • 在SSM中配置了事务控制但没生效的问题

    在SSM中配置了事务控制但没生效的问题

    这篇文章主要介绍了在SSM中配置了事务控制但没生效的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • JavaWeb项目中DLL文件动态加载方法

    JavaWeb项目中DLL文件动态加载方法

    在JavaWeb项目中,有时候我们需要在运行时动态加载DLL文件(在Windows中是DLL,在Linux中是SO文件),这通常用于实现一些特定的功能,比如调用本机代码或者使用某些特定于操作系统的API,本文将介绍如何在JavaWeb项目中动态加载DLL文件,需要的朋友可以参考下
    2024-12-12
  • java中char类型转换成int类型的2种方法

    java中char类型转换成int类型的2种方法

    这篇文章主要给大家介绍了关于java中char类型转换成int类型的2种方法,因为java是一门强类型语言,所以在数据运算中会存在类型转换,需要的朋友可以参考下
    2023-07-07
  • 8个简单部分开启Java语言学习之路 附java学习书单

    8个简单部分开启Java语言学习之路 附java学习书单

    8个简单部分开启Java语言学习之路,附java学习书单,这篇文章主要向大家介绍了学习java语言的方向,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • Mybatis省略@Param注解原理分析

    Mybatis省略@Param注解原理分析

    这篇文章主要介绍了Mybatis省略@Param注解原理分析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • MyBatis中criteria的or(或查询)语法说明

    MyBatis中criteria的or(或查询)语法说明

    这篇文章主要介绍了MyBatis中criteria的or(或查询)语法说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Eclipse中使用Maven创建Java Web工程的实现方式

    Eclipse中使用Maven创建Java Web工程的实现方式

    这篇文章主要介绍了Eclipse中使用Maven创建Java Web工程的实现方式的相关资料,希望通过本文能帮助到大家,让大家实现这样的方式,需要的朋友可以参考下
    2017-10-10
  • Java基础巩固系列包装类代码实例

    Java基础巩固系列包装类代码实例

    这篇文章主要介绍了Java包装类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04

最新评论