Java Hash Calculate getHash(File file)

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

Description

Return the MD5 hash for the given file.

License

Open Source License

Parameter

Parameter Description
file The file to read and process.

Return

the hash value of the file

Declaration

public static byte[] getHash(File file) 

Method Source Code

//package com.java2s;
/*/*  w  w  w .j a va  2  s . c  om*/
 * Copyright (c) 2006 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial API and implementation
 */

import java.io.Closeable;
import java.io.DataInputStream;

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

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

import java.io.OutputStream;

import java.io.Reader;

import java.io.Writer;

import java.security.MessageDigest;

public class Main {
    /** The MD5 Message Digest we use to calculate file hashes */
    static MessageDigest md;

    /**
     * Return the MD5 hash for the given file.
     * 
     * <p>This reads in the file and computes the MD5 hash for its contents. The
     * hash can be compared to the hash values of other files to determine if 
     * their contents are equivalent.  It is possible to detect duplicate files 
     * by computing the hash values for all the files in a given set and testing 
     * their equivalence.</p> 
     * 
     * @param file The file to read and process.
     * 
     * @return the hash value of the file
     */
    public static byte[] getHash(File file) {
        synchronized (md) {
            byte[] dataBytes = new byte[1024];

            if (file != null && file.exists() && file.canRead() && file.isFile()) {
                try (FileInputStream fis = new FileInputStream(file);) {
                    md.reset();
                    int nread = 0;
                    while ((nread = fis.read(dataBytes)) != -1) {
                        md.update(dataBytes, 0, nread);
                    }
                    ;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                byte[] mdbytes = md.digest();

                return mdbytes;
            } else {
                return new byte[0];
            }
        }
    }

    /**
     * Read the entire file into memory as an array of bytes.
     *
     * @param file The file to read
     *
     * @return A byte array that contains the contents of the file.
     *
     * @throws IOException If problems occur.
     */
    public static byte[] read(final File file) throws IOException {
        if (file == null) {
            throw new IOException("File reference was null");
        }

        if (file.exists() && file.canRead()) {
            DataInputStream dis = null;
            final byte[] bytes = new byte[new Long(file.length()).intValue()];

            try {
                dis = new DataInputStream(new FileInputStream(file));

                dis.readFully(bytes);

                return bytes;
            } catch (final Exception ignore) {
            } finally {
                // Attempt to close the data input stream
                try {
                    if (dis != null) {
                        dis.close();
                    }
                } catch (final Exception ignore) {
                }
            }
        }

        return null;
    }

    /**
     * Close the Reader quietly consuming any exceptions.
     * 
     * @param reader the Reader to close
     */
    public static void close(final Reader reader) {
        close((Closeable) reader);
    }

    /**
     * Close the Writer quietly consuming any exceptions.
     * 
     * @param writer the writer to close
     */
    public static void close(final Writer writer) {
        close((Closeable) writer);
    }

    /**
     * Close the input stream quietly consuming any exceptions.
     * 
     * @param is the input stream to close
     */
    public static void close(final InputStream is) {
        close((Closeable) is);
    }

    /**
     * Close the output stream quietly consuming any exceptions.
     * 
     * @param os the output stream to close
     */
    public static void close(final OutputStream os) {
        close((Closeable) os);
    }

    /**
     * Close the given group of closable objects quietly consuming 
     * any exceptions.
     * 
     * @param closeables the closable objects to close
     */
    public static void close(final Closeable... closeables) {
        if (closeables == null) {
            return;
        }
        for (final Closeable closeable : closeables) {
            close(closeable);
        }
    }

    /**
     * Closes a {@code Closeable} object quietly consuming any exceptions thrown. 
     * @param closeable the object to close, may be null or already closed
     */
    public static void close(final Closeable closeable) {
        try {
            if (closeable != null)
                closeable.close();
        } catch (final IOException ignore) {
        }
    }
}

Related

  1. getHash(byte[] data)
  2. getHash(byte[] data)
  3. getHash(byte[] data, int offset, int length)
  4. getHash(byte[] inputBytes)
  5. getHash(byte[]... bytesToHash)
  6. getHash(File file, String hashType)
  7. getHash(final byte[] data, final String hashAlgorithm)
  8. getHash(final String text, final Charset charset, final MessageDigest algorithm)
  9. getHash(InputStream in, String algorithm)