JAVA獲取文件MD5校驗值

JAVA獲取文件MD5校驗值 JAVA字節數組轉16進制字符串

    /**
     * 獲取文件MD5
     *
     * @param path
     * @return
     */
    public static String getFileMD5(String path) {
        /**
         * if use BigInteger
         * real 00667580b5ea2559d5a9ea86aebaceed
         * but 667580b5ea2559d5a9ea86aebacaeed
         */
//        BigInteger bi = null;
        String strMd5 = null;
        try {
            byte[] buffer = new byte[8192];
            int len = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            fis.close();
            byte[] b = md.digest();
//            bi = new BigInteger(1, b);
            strMd5 = bytesToHexStr(b);
        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
            Log.e("MyDigestUtils", e.getMessage());
        } catch (IOException e) {
//            e.printStackTrace();
            Log.e("MyDigestUtils", e.getMessage());
        }
//        return bi == null ? null : bi.toString(16);
        return strMd5;
    }
    
  /**
     * 字節數組轉十六進制字符串
     * @param b 字節數組
     * @return 十六進制字符串
     */
    public static String bytesToHexStr(byte[] b) {
        StringBuilder strBuilder = new StringBuilder();
        String strTemp = "";
        for (int n = 0; n < b.length; ++n) {
            strTemp = (Integer.toHexString(b[n] & 0XFF));
            if (strTemp.length() == 1) {
                strBuilder.append("0").append(strTemp);
            } else {
                strBuilder.append(strTemp);
            }
        }
        return strBuilder.toString();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章