Java MD5 File computeMd5Digest(final File file)

Here you can find the source of computeMd5Digest(final File file)

Description

Returns the MD5 hash of the given file.

License

Apache License

Parameter

Parameter Description
file a file

Exception

Parameter Description
IOException if the MD5 hash could not be computed

Return

the MD5 hash

Declaration

public static byte[] computeMd5Digest(final File file) throws IOException 

Method Source Code

//package com.java2s;
/*//from   w w  w.  j  av  a  2s  .c  o  m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.File;
import java.io.FileInputStream;

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

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

public class Main {
    /**
     * Returns the MD5 hash of the given file.
     *
     * @param file a file
     * @return the MD5 hash
     * @throws IOException if the MD5 hash could not be computed
     */
    public static byte[] computeMd5Digest(final File file) throws IOException {
        try (final FileInputStream fis = new FileInputStream(file)) {
            return computeMd5Digest(fis);
        }
    }

    /**
     * Returns the MD5 hash of the given stream.
     *
     * @param stream an input stream
     * @return the MD5 hash
     * @throws IOException if the MD5 hash could not be computed
     */
    public static byte[] computeMd5Digest(final InputStream stream) throws IOException {
        final MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (final NoSuchAlgorithmException nsae) {
            throw new IOException(nsae);
        }

        int len;
        final byte[] buffer = new byte[8192];
        while ((len = stream.read(buffer)) > -1) {
            if (len > 0) {
                digest.update(buffer, 0, len);
            }
        }

        return digest.digest();
    }
}

Related

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