java比较两个文件是否相同

1.需要引入的Jar包

1.需要引入的Jar包

<dependency>

<groupId>commons-codec</groupId>

<artifactId>commons-codec</artifactId>

<version>1.11</version>

</dependency>

 

/**

 * 判断两个文件是否相等(我这个文件一个是参数另一个是从集合里获取的)

 * @return boolean true 相等

 * @throws IOException

 */

private static boolean chechFile(File file1){

InputStream fileStream1 = null;

InputStream fileStream2 = null;

try {

Iterator<File> it = fileList.iterator();

while (it.hasNext()) {

File file2 = it.next();

if (file1.length() != file2.length()) {

return false;

}

//根据文件名判断的可以根据需求进行修改

if(file1.getName().equals(file2.getName())){

return true;

}

fileStream1 = new FileInputStream(file1);

fileStream2 = new FileInputStream(file2);

//InputStream 转 byte[]

byte[] fileByteArray = new byte[fileStream1.available()];

return isSameFiles(fileByteArray, new byte[fileStream2.available()]);

}

return false;

}catch (Exception e){

e.printStackTrace();

log.info("比较文件出错{}",e);

return false;

} finally {

//记得关闭文件流否则就没办法操作文件了

try {

if (fileStream1 != null){

fileStream1.close();

}

if (fileStream2 != null){

fileStream2.close();

}

}catch (Exception e){

e.printStackTrace();

log.info("关闭异常{}",e);

}


}

}




/**

 * 验证两个文件字节流是否相等

 * @return boolean true 相等

 * @throws IOException

 */

private static boolean isSameFiles(byte[] fileByte1, byte[] fileByte2) {

String firstFileMd5 = DigestUtils.md5Hex(fileByte1);

String secondFileMd5 = DigestUtils.md5Hex(fileByte2);

if (firstFileMd5.equals(secondFileMd5)) {

System.out.println("—- equals —— md5 " + firstFileMd5);

return true;

} else {

System.out.println(firstFileMd5 + " is firstFileMd5 ++ unequal ++ secondFileMd5 = " + secondFileMd5);

return false;

}

}

————————————————

版权声明:本文为CSDN博主「用生命在耍帅ㅤ」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_43583693/article/details/115668640