獲取大檔案MD5值(JAVA)
阿新 • • 發佈:2018-11-13
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
package com.topcheer;import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 計算大檔案MD5
* David 2012-10-12
*/
public class GetBigFileMD5 {
static MessageDigest MD5 = null;
static {
try {
} catch (NoSuchAlgorithmException ne) {
ne.printStackTrace();
}
}
/**
* 對一個檔案獲取md5值
* @return md5串
*/
public static String getMD5(File file) {
FileInputStream fileInputStream = null;
try {
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
}
return new String(Hex.encodeHex(MD5.digest()));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 求一個字串的md5值
* @param target 字串
* @return md5 value
*/
public static String MD5(String target) {
return DigestUtils.md5Hex(target);
}
public static void main(String[] args){
long beginTime =System.currentTimeMillis();
File fileZIP = new File("D:/TEST/IMAGE2.zip");
String md5=getMD5(fileZIP);
long endTime =System.currentTimeMillis();
System.out.println("MD5:"+md5+"\n time:"+((endTime-beginTime)/1000)+"s");
}
}