java获取文 件的MD5值

有两种解决方案,一种是用MessageDigest来实现,另种是用org.apache.commons.codec.digest来实现,下面是代码:

package com.creditease.mobile.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

import org.apache.commons.codec.digest.*;
import org.apache.commons.io.IOUtils;

public class MD5Util {
	/**
	 * 用MessageDigest获取文件的md5值
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String getMd5ByMessageDigest(String filePath) throws FileNotFoundException {
		File file = new File(filePath);
		String value = null;
		FileInputStream in = new FileInputStream(file);
		try {
			MappedByteBuffer byteBuffer = in.getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}
	/**
	 * 用DigestUtils去获取MD5值
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static String getMd5ByDigestUtils(String filePath) throws IOException{
		FileInputStream fis = new FileInputStream(filePath);
		String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
		IOUtils.closeQuietly(fis);
		return md5;
	}
	public static void main(String[] args) throws IOException {
		String path = "E:\\msdia80.dll";
		int count = 3000;
		String v = "";
		long s1 = System.currentTimeMillis();
		for(int i=0;i<count;i++){
			v = getMd5ByMessageDigest(path);
		}
		long e1 = System.currentTimeMillis();
		System.out.println("MD5:" + v.toUpperCase()+",耗时:"+(e1-s1)+"毫秒");
		
		String v1 = "";
		long s2 = System.currentTimeMillis();
		for(int i=0;i<count;i++){
			v1 = getMd5ByDigestUtils(path);
		}
		long e2 = System.currentTimeMillis();
		System.out.println("MD5:"+v1+",耗时:"+(e2-s2)+"毫秒");
	}
 
}

测试结果:


由此可以看出用jdk 的java.security.MessageDigest效率上要比org.apache.commons.codec.digest.*这个高一些。


阅读更多
个人分类: 善假于物
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭