Java MD5 File computeMD5(String filename)

Here you can find the source of computeMD5(String filename)

Description

compute MD

License

Apache License

Declaration

public static String computeMD5(String filename) throws NullPointerException,
            java.security.NoSuchAlgorithmException, java.io.IOException, java.io.FileNotFoundException 

Method Source Code


//package com.java2s;
/*// w w  w  .j a v a2  s  . co  m
 * Copyright 2010 the original author or authors.
 * Copyright 2010 SorcerSoft.org.
 *  
 * Licensed under the Apache 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.apache.org/licenses/LICENSE-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.ByteArrayOutputStream;
import java.io.FileInputStream;

import java.security.MessageDigest;

public class Main {
    public static String computeMD5(String filename) throws NullPointerException,
            java.security.NoSuchAlgorithmException, java.io.IOException, java.io.FileNotFoundException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream ifs = new FileInputStream(filename);
        ByteArrayOutputStream byteOutput = null;
        StringBuffer hexString = new StringBuffer();
        byte[] bytes = new byte[1024];
        int read;

        byteOutput = new ByteArrayOutputStream();
        while ((read = ifs.read(bytes)) > -1)
            byteOutput.write(bytes, 0, read);
        byte[] filebytes = byteOutput.toByteArray();
        // System.out.println("the files string is = "+new String(filebytes));
        byte[] hash = md.digest(filebytes);
        for (int i = 0; i < hash.length; i++) {
            hexString.append(Integer.toHexString(0xFF & hash[i]));
        }
        // System.out.println("HextSring="+hexString.toString());
        return hexString.toString();// new String(hash, "UTF-8");
    }
}

Related

  1. computeMD5(File file)
  2. computeMD5(File file)
  3. computeMD5(final File file)
  4. computeMd5Digest(final File file)
  5. computeMD5Sum(final File file)