Java读取文件MD5值

新逸网络 1.5K 2
public class TestMD5 {

    public static final String HASH_TYPE_MD5 = "MD5";
    public static final String HASH_TYPE_SHA1 = "SHA-1";
    public static final String HASH_TYPE_SHA256 = "SHA-256";
    public static final String HASH_TYPE_SHA384 = "SHA-384";
    public static final String HASH_TYPE_SHA512 = "SHA-512";

    public static String getMd5ByFile(File file) throws FileNotFoundException {
        return getMd5ByFile(file, HASH_TYPE_MD5);
    }

    public static String getMd5ByFile(File file, String hashType) throws FileNotFoundException {
        String value = null;
        FileInputStream fis = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest digest = MessageDigest.getInstance(hashType);
            digest.update(byteBuffer);
            BigInteger bigInteger = new BigInteger(1, digest.digest());
            value = bigInteger.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    public static void main(String[] args) throws IOException {

        String path = "E:\\md5-test.zip";

        // apache commons解决方案
        long s1 = System.currentTimeMillis();
        String v = getMd5ByFile(new File(path));
        System.out.println("MD5: " + v.toUpperCase());
        long s2 = System.currentTimeMillis();
        System.out.println(s2 - s1);

        // jdk解决方案
        long s3 = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream(path);
        String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
        IOUtils.closeQuietly(fis);
        System.out.println("MD5:" + md5.toUpperCase());
        long s4 = System.currentTimeMillis();
        System.out.println(s4 - s3);

        // System.out.println("MD5:"+DigestUtils.md5Hex("JAVA"));
    }
}

发表评论 取消回复
表情 图片 链接 代码

  1. Ha Lv 1

    哈哈[aru_3]

分享