关闭

java获取文 件的MD5值

126人阅读 评论(0) 收藏 举报
分类:

有两种解决方案,一种是用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.*这个高一些。


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65938次
    • 积分:1365
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:97篇
    • 译文:0篇
    • 评论:1条
    最新评论