java求文件MD5值

来源:互联网 发布:eve 作战网络 编辑:程序博客网 时间:2024/06/08 06:57
import java.io.FileInputStream;import java.io.IOException;import java.security.DigestInputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class FileMD5 {public static void main(String[] args) {long startTime = System.currentTimeMillis();try {System.out.println(fileMD5("F:\\TDDOWNLOAD\\123.rar"));//BDEAE194A93C186B7B42A7A6347B6310} catch (IOException e) {e.printStackTrace();}long endTime = System.currentTimeMillis();System.out.println((endTime - startTime) / 1000);}public static String fileMD5(String inputFile) throws IOException {// 缓冲区大小(这个可以抽出一个参数)int bufferSize = 256 * 1024;FileInputStream fileInputStream = null;DigestInputStream digestInputStream = null;try {// 拿到一个MD5转换器(同样,这里可以换成SHA1)MessageDigest messageDigest = MessageDigest.getInstance("MD5");// 使用DigestInputStreamfileInputStream = new FileInputStream(inputFile);digestInputStream = new DigestInputStream(fileInputStream,messageDigest);// read的过程中进行MD5处理,直到读完文件byte[] buffer = new byte[bufferSize];while (digestInputStream.read(buffer) > 0);// 获取最终的MessageDigestmessageDigest = digestInputStream.getMessageDigest();// 拿到结果,也是字节数组,包含16个元素byte[] resultByteArray = messageDigest.digest();// 同样,把字节数组转换成字符串return byteArrayToHex(resultByteArray);} catch (NoSuchAlgorithmException e) {return null;} finally {try {digestInputStream.close();} catch (Exception e) {e.printStackTrace();}try {fileInputStream.close();} catch (Exception e) {e.printStackTrace();}}}// 下面这个函数用于将字节数组换成成16进制的字符串public static String byteArrayToHex(byte[] byteArray) {// 首先初始化一个字符数组,用来存放每个16进制字符char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' };// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))char[] resultCharArray = new char[byteArray.length * 2];// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去int index = 0;for (byte b : byteArray) {resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];resultCharArray[index++] = hexDigits[b & 0xf];}// 字符数组组合成字符串返回return new String(resultCharArray);}}

原创粉丝点击