Java计算MD5值

计算文件的MD5值
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;


	static String generateMD5(String path) throws Exception
	{
		String strMD5 = null;
		File file = new File(path);
		FileInputStream in = new FileInputStream(file);
		MappedByteBuffer buffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		MessageDigest digest = MessageDigest.getInstance("md5");
		digest.update(buffer);
		in.close();
		
		byte[] byteArr = digest.digest();
		BigInteger bigInteger = new BigInteger(1, byteArr);
		strMD5 = bigInteger.toString(16);
		return strMD5;
	}
	
	static String generateMD54ByteArray(String path) throws Exception
	{
		String strMD5 = null;
		MessageDigest digest = MessageDigest.getInstance("md5");
		InputStream in = new FileInputStream(path);
		byte[] buff = new byte[1024];
		int size = -1;
		while((size=in.read(buff))!=-1)
		{
			digest.update(buff, 0, size);
		}
		in.close();
		BigInteger bigInteger = new BigInteger(1, digest.digest());
		strMD5  = bigInteger.toString(16);
		return strMD5;
	}

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