java求檔案MD5值

來源:互聯網
上載者:User
import java.io.FileInputStream;import java.io.IOException;import java.security.DigestInputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class FileMD5 {public static void main(String[] args) {long startTime = System.currentTimeMillis();try {System.out.println(fileMD5("F:\\TDDOWNLOAD\\123.rar"));//BDEAE194A93C186B7B42A7A6347B6310} catch (IOException e) {e.printStackTrace();}long endTime = System.currentTimeMillis();System.out.println((endTime - startTime) / 1000);}public static String fileMD5(String inputFile) throws IOException {// 緩衝區大小(這個可以抽出一個參數)int bufferSize = 256 * 1024;FileInputStream fileInputStream = null;DigestInputStream digestInputStream = null;try {// 拿到一個MD5轉換器(同樣,這裡可以換成SHA1)MessageDigest messageDigest = MessageDigest.getInstance("MD5");// 使用DigestInputStreamfileInputStream = new FileInputStream(inputFile);digestInputStream = new DigestInputStream(fileInputStream,messageDigest);// read的過程中進行MD5處理,直到讀完檔案byte[] buffer = new byte[bufferSize];while (digestInputStream.read(buffer) > 0);// 擷取最終的MessageDigestmessageDigest = digestInputStream.getMessageDigest();// 拿到結果,也是位元組數組,包含16個元素byte[] resultByteArray = messageDigest.digest();// 同樣,把位元組數群組轉換成字串return byteArrayToHex(resultByteArray);} catch (NoSuchAlgorithmException e) {return null;} finally {try {digestInputStream.close();} catch (Exception e) {e.printStackTrace();}try {fileInputStream.close();} catch (Exception e) {e.printStackTrace();}}}// 下面這個函數用於將位元組數組換成成16進位的字串public static String byteArrayToHex(byte[] byteArray) {// 首先初始化一個字元數組,用來存放每個16進位字元char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };// new一個字元數組,這個就是用來組成結果字串的(解釋一下:一個byte是八位二進位,也就是2位十六進位字元(2的8次方等於16的2次方))char[] resultCharArray = new char[byteArray.length * 2];// 遍曆位元組數組,通過位元運算(位元運算效率高),轉換成字元放到字元數組中去int index = 0;for (byte b : byteArray) {resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];resultCharArray[index++] = hexDigits[b & 0xf];}// 字元數組組合成字串返回return new String(resultCharArray);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.