How to Create File Checksum Value in Java


In this example we will show two methods to generate a file checksum value in Java.

Source Code

1) Using java.security.MessageDigest

package com.beginner.examples;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileOperator22Example { 
	public static void main(String[] args) throws NoSuchAlgorithmException{

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        int content;
        String result="";
        try
        {
        	InputStream in = new FileInputStream("example.txt");
            byte[] buffer = new byte[1024];
            while ((content = in.read(buffer)) != -1) 
            {
                md5.update(buffer, 0, content);
            }
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        for (byte b : md5.digest())
        {
            result += String.format("%02x", b);
        }
        String checknum = result.toString();
        System.out.println(checknum);
    }
}

Output:

e76f8a2f7ae08dfa86df819e7d7639c3

2) Using org.apache.commons.codec.digest.DigestUtils

package com.beginner.examples;

import java.io.*;
import org.apache.commons.codec.digest.DigestUtils;

public class FileOperator23Example { 
	public static void main(String[] args) throws IOException{

		FileInputStream in = new FileInputStream("example.txt");
		String checknum = DigestUtils.md5Hex(in);
        System.out.println(checknum);
    }
}

Output:

e76f8a2f7ae08dfa86df819e7d7639c3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments