Java MD5 String md5(File f)

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

Description

md

License

Educational Community License

Declaration

public static final String md5(File f) throws IOException 

Method Source Code

//package com.java2s;
/**//from  w  w  w .j ava2s .c  om
 *  Copyright 2009, 2010 The Regents of the University of California
 *  Licensed under the Educational Community License, Version 2.0
 *  (the "License"); you may not use this file except in compliance
 *  with the License. You may obtain a copy of the License at
 *
 *  http://www.osedu.org/licenses/ECL-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS IS"
 *  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 *  or implied. See the License for the specific language governing
 *  permissions and limitations under the 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 {
    public static final String md5(File f) throws IOException {
        byte[] bytes = new byte[1024];
        InputStream is = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            is = new DigestInputStream(new FileInputStream(f), md);
            while ((is.read(bytes)) >= 0) {
            }
            return hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("No MD5 algorithm available");
        } finally {
            is.close();
        }
    }

    /**
     * Converts the checksum to a hex string.
     * 
     * @param data
     *          the digest
     * @return the digest hex representation
     */
    private static String hex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }
}

Related

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