Java MD5 String md5(File f)

Here you can find the source of md5(File f)

Description

md

License

Apache License

Declaration

public static String md5(File f) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    final protected static char[] hexArray = "0123456789abcdef".toCharArray();

    public static String md5(File f) {
        try {/*  w  ww  .  j  ava  2  s .  co  m*/
            byte[] buf = new byte[1024];
            MessageDigest md = MessageDigest.getInstance("MD5");
            try (InputStream is = new FileInputStream(f); DigestInputStream dis = new DigestInputStream(is, md);) {
                while (dis.read(buf) >= 0)
                    ;
            }
            byte[] digest = md.digest();
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}

Related

  1. md5()
  2. md5(File f)
  3. md5(File f)
  4. md5(File f)
  5. md5(File file)
  6. md5(File file)