import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.twmacinta.util.MD5; //fast-md5.jar
public class Checksum {
private static MD5 md5 = new MD5();
private static byte[] buffer = new byte[1024];
private static int numRead;
private static FileInputStream fis;
private static ObjectInputStream ois;
private Checksum(){}
/**
* get checksum from a FILE on DISK
* @param filename
* @return
* @throws Exception
*/
public static String getChecksum(String filename) throws Exception{
fis = new FileInputStream(filename);
updateMD5WithStream(fis);
return md5.asHex();
}
public static String getChecksum(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
updateMD5WithStream(bais);
return md5.asHex();
}
private static void updateMD5WithStream(InputStream st) throws IOException{
md5.Init();
do {
numRead = st.read(buffer);
if (numRead > 0) {
md5.Update(buffer, 0, numRead);
}
} while (numRead != -1);
st.close();
}
}