add IO.md5(InputStream)

This commit is contained in:
Timi
2025-10-24 11:58:28 +08:00
parent c0b4f41ea4
commit cd9eee61f3

View File

@ -1029,15 +1029,23 @@ public class IO implements OS.FileSystem {
*
* @param file 文件
* @return MD5
* @throws NoSuchAlgorithmException JDK 不支持此算法
*/
public static String md5(File file) throws NoSuchAlgorithmException {
try {
public static String md5(File file) throws FileNotFoundException {
return md5(getInputStream(file));
}
/**
* 计算输入流 MD5
*
* @param stream 输入流
* @return MD5
*/
public static String md5(InputStream stream) {
try (stream) {
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = getInputStream(file);
byte[] buffer = new byte[8192];
int l;
while ((l = is.read(buffer)) != -1) {
while ((l = stream.read(buffer)) != -1) {
md.update(buffer, 0, l);
}
byte[] bytes = md.digest();
@ -1046,9 +1054,8 @@ public class IO implements OS.FileSystem {
chars[j++] = Text.HEX_DIGITS_LOWER[bytes[i] >>> 4 & 0xF];
chars[j++] = Text.HEX_DIGITS_LOWER[bytes[i] & 0xF];
}
is.close();
return new String(chars);
} catch (IOException e) {
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}