java計算檔案的MD5值
阿新 • • 發佈:2019-02-19
網上找的JAVA計算檔案的MD5值的工具類,儲存下做個記錄。
package phreadpool; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; public class FileMDFive { public static void main(String[] args) { System.out.println(FileMDFive.getFileMD5(new File("D:\\api.docx"))); } /** * 根據檔案計算出檔案的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[1024]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer, 0, 1024)) != -1) { digest.update(buffer, 0, len); } in.close(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } /** * 獲取資料夾中的檔案的MD5值 * @param file * @param listChild * @return */ public static Map<String,String> getDirMD5(File file, boolean listChild){ if(! file.isDirectory()){ return null; } Map<String, String> map = new HashMap<String, String>(); String md5; File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File file2 = files[i]; if(file2.isDirectory() && listChild){ map.putAll(getDirMD5(file2, listChild)); }else{ md5 = getFileMD5(file2); if(md5 != null){ map.put(file2.getPath(), md5); } } } return map; } }