JAVA生成文件的md5校驗值


 

這里使用了lombok打印日志,也可以不用

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import lombok.extern.slf4j.Slf4j;
/**
 * author yvioo
 */
@Slf4j
public class MD5Util {
     /**
      * 生成文件的md5校驗值
      * 
      * @param path 文件路徑
      * @return 文件md5校驗值
      * @throws IOException
     * @throws NoSuchAlgorithmException 
      */
    public static String getFileMD5String(String path){
        InputStream fis = null;
        MessageDigest messagedigest = null;
        try {
            messagedigest = MessageDigest.getInstance("md5");
            File file = new File(path);
            if(!file.exists() || !file.isFile()) {
                log.error("不存在或不是一個文件");
                return "";
            }
            
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
               messagedigest.update(buffer, 0, numRead);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }finally {
            try {
                if(fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bufferToHex(messagedigest.digest());
    }
    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }
    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
         appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }
    /**
     * 默認的密碼字符串組合,用來將字節轉換成 16 進制表示的字符,apache校驗下載的文件的正確性用的就是默認的這個組合
     */
    protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
     char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字節中高 4 位的數字轉換, >>> 為邏輯右移,將符號位一起右移,此處未發現兩種符號有何不同 
     char c1 = hexDigits[bt & 0xf];// 取字節中低 4 位的數字轉換 
     stringbuffer.append(c0);
     stringbuffer.append(c1);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM