Java MD5 String md5fromFile(String path)

Here you can find the source of md5fromFile(String path)

Description

This function is passed a File name and it returns a md5 hash of this file.

License

Open Source License

Parameter

Parameter Description
FileToMd5 a parameter

Return

The md5 string

Declaration

public static String md5fromFile(String path) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009 Richard Malek and SEAGE contributors
    /*from   w w w.  j  av  a 2 s .  c om*/
 * This file is part of SEAGE.
    
 * SEAGE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
    
 * SEAGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
    
 * You should have received a copy of the GNU General Public License
 * along with SEAGE. If not, see <http://www.gnu.org/licenses/>.
 *
 */

import java.io.File;
import java.io.FileInputStream;

import java.io.InputStream;

import java.math.BigInteger;
import java.security.MessageDigest;

public class Main {
    /**
    * This function is passed a File name and it returns a md5 hash of
    * this file.
    * @param FileToMd5
    * @return The md5 string
    */
    public static String md5fromFile(String path) throws Exception {
        return md5fromFile(new File(path));
    }

    public static String md5fromFile(File file) throws Exception {
        return md5(new FileInputStream(file));
    }

    private static String md5(InputStream is) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[8192];
        int read = 0;

        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);

        is.close();

        return output;
    }
}

Related

  1. md5Encrypt(String str)
  2. md5Encryption(String str)
  3. md5File(File f)
  4. md5file(File file)
  5. md5FromFile(File file)
  6. md5Hex(String data)
  7. md5Hex(String data)
  8. md5Hex(String message)
  9. md5Hex(String message)