How to get MD5 checksum for a file in Java

Published on March 22, 2016 by Daniel Lanza


MD5 checksum is a 128-bit hash value (32 digit hexadecimal number). This works as a fingerprint for a file which let us compare together other files to find out duplicate files.

These Java classes will let us calculate MD5 checksum for any single file.

Maven dependencies


MD5 Java class

package com.dalanz.file;


import org.apache.commons.codec.digest.DigestUtils;

public class GetMD5ForFile {

    private File file;

    public GetMD5ForFile(String filePath) {
        this.file = new File(filePath);

    public GetMD5ForFile(File file) {
        this.file = file;

    public String getMD5() {
        String md5 = null;

        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(this.file);

            // md5Hex converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
            // The returned array will be double the length of the passed array, as it takes two characters to represent any given byte.

            md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fileInputStream));


        } catch (IOException e) {

        return md5;

Main class


import com.dalanz.file.GetMD5ForFile;

public class test {

    public static void main(String[] args) {

        String filePath = "/Users/dlanza/Desktop/Test.txt";

        GetMD5ForFile file = new GetMD5ForFile(filePath);

        System.out.println("MD5: " + file.getMD5());


MD5: 6cbca9b36efc68e359df0d66338e0141
comments powered by Disqus

See also

How to set JAVA_HOME on Mac OS X

If you are planing to develop Java Apps on your Mac, you may have to set $JAVA_HOME environment variable. Install the latest Java Virtual Machine Go to How to install JDK on Mac OS X) to install a new Java Virtual Machine. Download the latest Java JDK package from Oracle. Check Java Virtual Machines List directories in the following root -> /Library/Java/JavaVirtualMachines $ ls -l /Library/Java/JavaVirtualMachines drwxr-xr-x 3 root wheel 102 23 dic 20:36 jdk1.

Read more

How to resolve 404 error with Tomcat Server and Eclipse

If you start Tomcat from Eclipse and get a 404-Error code when you go to http://localhost:8080, there is a easy way to fix the issue. Just go to Properties for Tomcat (right click on Tomcat - Servers Tab) Switch location Tomcat Properties Switch location from [workspace metadata] to [/Servers/Tomcat v…] Restart Tomcat from Eclipse and go back to http://localhost:8080. You will see Tomcat configuration page. Tomcat configuration page

Read more