Thursday, June 26, 2008

Calculate CheckSum using Java

Some times we need to calculte checksum of specified file. In java, We can use MessageDigest class to get checksum of specified file.

Sample Java Code

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CheckSum {
public static void main(String args[]){
StringBuffer checksum;
try {
File file = new File("C:\\Test.zip");
FileInputStream is = new FileInputStream(file);
byte buffer[] = new byte[(int)file.length()];
is.read(buffer);
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(buffer);
byte digest[] = md.digest();
checksum = new StringBuffer();
for(int i = 0; i <>
{
String digit = Integer.toHexString(0xff & digest[i]);
if(digit.length() == 1)
checksum.append('0');
checksum.append(digit);
}
System.out.println("checksum::"+checksum.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

0 Java Junction comments: