Java MD5 Sum md5sum(File file)

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

Description

mdsum

License

Open Source License

Declaration

public static String md5sum(File file) throws NoSuchAlgorithmException, FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
/*/*from w w  w  .j av  a  2  s .  co  m*/
 * Utils.java - Created on Feb 2, 2004
 * 
 * Copyright (C) 2003-2004 Sebastian Rodriguez
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
    
 * This library 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
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Last Update: $Date: 2004/03/12 17:25:14 $
 */

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

import java.io.IOException;
import java.io.InputStream;

import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String md5sum(File file) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        return createMD5(new FileInputStream(file));
    }

    private static String createMD5(final InputStream data) throws NoSuchAlgorithmException, IOException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        DigestInputStream dis = new DigestInputStream(data, md5);
        while (dis.read() != -1) {
            ;
        }
        dis.close();
        data.close();

        byte[] fileDigest = md5.digest();
        StringBuffer checksumSb = new StringBuffer();
        for (int i = 0; i < fileDigest.length; i++) {
            String hexStr = Integer.toHexString(0x00ff & fileDigest[i]);
            if (hexStr.length() < 2) {
                checksumSb.append("0");
            }
            checksumSb.append(hexStr);
        }
        return checksumSb.toString();
    }
}

Related

  1. md5sum(byte[] input, int length)
  2. MD5Sum(byte[] par1Data)
  3. md5sum(File f)
  4. md5sum(File f, char[] cbuf, MessageDigest digest, byte[] bbuf)
  5. md5sum(File file)
  6. md5sum(File library)
  7. md5sum(InputStream file)
  8. md5sum(InputStream in)
  9. md5sum(String data)