md5 大文件 java,使用Java为大文件生成MD5非常慢

I am using Java to generate the MD5 hash for some files. I need to generate one MD5 for several files with a total size of about 1 gigabyte.

Here's my code:

private String generateMD5(SequenceInputStream inputStream){

if(inputStream==null){

return null;

}

MessageDigest md;

try {

int read =0;

byte[] buf = new byte[2048];

md = MessageDigest.getInstance("MD5");

while((read = inputStream.read(buf))>0){

md.update(buf,0,read);

}

byte[] hashValue = md.digest();

return new String(hashValue);

} catch (NoSuchAlgorithmException e) {

return null;

} catch (IOException e) {

return null;

}finally{

try {

if(inputStream!=null)inputStream.close();

} catch (IOException e) {

// ...

}

}

}

This seems to run forever.

How can I make it more efficient?

解决方案

You may want to use the Fast MD5 library. It's much faster than Java's built-in MD5 provider and getting a hash is as simple as:

String hash = MD5.asHex(MD5.getHash(new File(filename)));

Be aware that the slow speed may also be due to slow File I/O.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用MD5算法生成校验文件MD5是一种常用的哈希算法,可以将任意长度的数据转换为固定长度的哈希值。生成MD5校验文件的过程可以通过以下步骤实现: 1. 读取需要生成校验文件文件内容。 2. 将文件内容进行MD5哈希计算,得到哈希值。 3. 将哈希值写入校验文件中。 在Java中,可以使用MessageDigest类来实现MD5哈希计算。具体实现可以参考以下代码: ``` import java.io.*;import java.security.*; public class MD5Util { public static String getFileMD5(File file) throws IOException, NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) != -1) { md5.update(buffer, 0, length); } fis.close(); byte[] digest = md5.digest(); StringBuilder sb = new StringBuilder(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } public static void main(String[] args) { long begin = System.currentTimeMillis(); File file = new File("test.txt"); try { String md5 = getFileMD5(file); long end = System.currentTimeMillis(); System.out.println("md5:" + md5 + " time:" + ((end - begin) / 1000) + "s"); } catch (IOException | NoSuchAlgorithmException e) { System.err.println(MD5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。"); } } } ``` 该代码可以读取文件内容并计算MD5哈希值,最后输出哈希值和计算时间。如果计算失败,则输出初始化失败的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值