import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
-
Create by tanx on 2019/4/30
*/
public class Md5Utils {
private static Logger LOG = LoggerFactory.getLogger(Md5Utils.class);
private static final int bufferSize = 16 * 1024;public static String fileMD5(String inputFilePath) throws IOException {
try (
FileInputStream fileInputStream = new FileInputStream(inputFilePath);
) {
return fileMD5(fileInputStream);
} catch (Exception e) {
return null;
}
}public static String fileMD5(File inputFile) throws IOException {
try (
FileInputStream fileInputStream = new FileInputStream(inputFile);
) {
return fileMD5(fileInputStream);
} catch (Exception e) {
return null;
}
}/**
- 可处理大文件
- @param inputStream
- @return
- @throws IOException
*/
public static String fileMD5(InputStream inputStream) throws IOException, NoSuchAlgorithmException {
// 拿到一个MD5转换器(同样,这里可以换成SHA1)
MessageDigest messageDigest = MessageDigest.getInstance(“MD5”);
try (
// 使用DigestInputStream
DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
) {
// read的过程中进行MD5处理,直到读完文件
byte[] buffer = new byte[bufferSize];
while (digestInputStream.read(buffer) > 0) ;
// 获取最终的MessageDigest
messageDigest = digestInputStream.getMessageDigest();
// 拿到结果,也是字节数组,包含16个元素
BigInteger bigInteger = new BigInteger(1, messageDigest.digest());
// 同样,把字节数组转换成字符串
return bigInteger.toString(16);
} catch (Exception e) {
return null;
}
}
}