I am rewriting your code using nio, the code is as follows:
private static String generateMD5(FileInputStream inputStream){ if(inputStream==null){ return null; } MessageDigest md; try { md = MessageDigest.getInstance("MD5"); FileChannel channel = inputStream.getChannel(); ByteBuffer buff = ByteBuffer.allocate(2048); while(channel.read(buff) != -1) { buff.flip(); md.update(buff); buff.clear(); } 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) { } } }
On my machine, it takes about 30 seconds to generate md5 code for a large file, and of course I will also check your code, the result indicates that nio does not improve program performance.
Then, I try to get the time for io and md5 respectively, statistics show that the slow io file is the bottleneck because io takes 5/6 of the time.
Using the Fast MD5 library mentioned by @Sticky, it only takes 15 seconds to generate the md5 code, the improvement is great.
Alanmars
source share