java快速比較兩個檔案是否相同
阿新 • • 發佈:2019-02-06
像百度網盤有秒傳的功能,其實他的原理主要是比較需要上傳的檔案和網盤中的檔案是否一樣,如果不一樣則上傳,如果一樣就沒必要上傳檔案,只是將網盤中的檔案指向你的使用者名稱即可,從而實現了秒傳。
通過計算檔案的MD5或SHA-1是否一致,程式碼如下
MD5演算法SHA1演算法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 String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[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(); } } }
獲取網路檔案的MD5
public static String getNetFileMD5(String path) throws Exception{ URL url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); InputStream inStream = con.getInputStream(); MessageDigest digest = null; byte buffer[] = new byte[8192]; int len; try { digest =MessageDigest.getInstance("MD5"); while ((len = inStream.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 { inStream.close(); } catch (Exception e) { e.printStackTrace(); } } }