大文件MD5值计算

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;




public class TestBigFileMD5 {
	private static final String FILE_NAME="";
	public static void main(String[] args) {
		long time1=System.currentTimeMillis();
		String md5=getFileMD5(new File(FILE_NAME));
		long time2=System.currentTimeMillis();
		System.out.println("MD5值"+md5+"    耗时:"+(time2-time1));
	}
	public static String getFileMD5(File file) {
		String md5=null;
		if (!file.isFile()) {
			return null;
		}
		MessageDigest digest = null;//messagedigest一定要为局部变量,为了保证线程安全。写成全局变量在多线程情况下,md5值计算将出现问题。
		FileInputStream in = null;
		byte buffer[] = new byte[8192];
		int len;
		try {
			digest =MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer)) != -1) {
				digest.update(buffer, 0, len);
			}
			BigInteger bigInt = new BigInteger(1, digest.digest());
			md5= bigInt.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return md5;
	}
}


 
 

你可能感兴趣的:(java基础)