Java MD5 String md5(File file)

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

Description

Md5.

License

Open Source License

Parameter

Parameter Description
file the file

Exception

Parameter Description
NoSuchAlgorithmException the no such algorithm exception
IOException Signals that an I/O exception has occurred.

Return

the string

Declaration

public static String md5(File file) throws NoSuchAlgorithmException, IOException 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**// w  ww.j a  v  a 2 s . c om
     * Md5.
     *
     * @param file
     *            the file
     * @return the string
     * @throws NoSuchAlgorithmException
     *             the no such algorithm exception
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static String md5(File file) throws NoSuchAlgorithmException, IOException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        InputStream is = new FileInputStream(file);

        is = new DigestInputStream(is, md);
        byte[] buf = new byte[2048];
        @SuppressWarnings("unused")
        int read;
        while ((read = is.read(buf)) != -1) {
            //
        }

        is.close();

        byte[] digest = md.digest();
        return new BigInteger(1, digest).toString(16);
    }

    /**
     * Md5.
     *
     * @param s
     *            the s
     * @return the string
     * @throws NoSuchAlgorithmException
     *             the no such algorithm exception
     */
    public static String md5(String s) throws NoSuchAlgorithmException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes(), 0, s.length());
        return new BigInteger(1, m.digest()).toString(16);
    }
}

Related

  1. md5(File f)
  2. md5(File f)
  3. md5(File f)
  4. md5(File f)
  5. md5(File file)
  6. md5(File file)
  7. md5(File gcdZipFile)
  8. md5(final File file)
  9. md5(final InputStream in)