如何比较两个文件是否相同
发布网友
发布时间:2022-04-20 11:47
我来回答
共1个回答
热心网友
时间:2023-09-12 20:54
计算MD5或SHA-1,一样的就是同一个文件
下面的代码,不需要额外使用第三方组件,且支持超大文件
// 计算文件的 MD5 值publicstatic String getFileMD5(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = newbyte[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(); } } }
// 计算文件的 SHA-1 值publicstatic String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = newbyte[8192]; int len; try { digest =MessageDigest.getInstance("SHA-1"); 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(); } }}