Java生成文件hash值(通过传入file或者InputStream)
package com.hczy.syncdata.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
public class FileHahUtil {
public static String hashFile(File file) throws Exception {
FileInputStream fis = null;
String sha256 = null;
try {
fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte buffer[] = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
byte[] digest = md.digest();
sha256 = byte2hexLower(digest);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("计算文件hash值错误");
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sha256;
}
private static String byte2hexLower(byte[] b) {
String hs = "";
String stmp = "";
for (int i = 0; i < b.length; i++) {
stmp = Integer.toHexString(b[i] & 0XFF);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs;
}
public static String md5HashCode(InputStream fis) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md.update(buffer, 0, length);
}
fis.close();
byte[] md5Bytes = md.digest();
BigInteger bigInt = new BigInteger(1, md5Bytes);
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static void main(String[] args) {
try {
File file = new File("D:\\file\\practice\\Downloads.rar");
File file1 = new File("D:\\file\\practice\\into\\Downloads.rar");
File file2 = new File("D:\\file\\practice\\into\\Downloads(1).rar");
File file3 = new File("D:\\file\\practice\\into\\Google.rar");
String md5HashCode = FileHahUtil.md5HashCode(new FileInputStream(file));
System.out.println(md5HashCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}