ローカルファイルのmd5をチェックする方法です。
先日ご紹介したS3でのmd5チェックと組み合わせることで、ローカルファイルのS3転送がうまくいったかどうかなどチェックが出来るようになります。
/**
* ローカルファイルMD5チェック
*
*/
public static String checkLocalFileMD5(File file) {
String digest = "";
try {
digest = createDigest(file);
} catch (NoSuchAlgorithmException e) {
throw new Md5CheckException(e);
} catch (IOException e) {
throw new Md5CheckException(e);
}
return digest;
}
/**
*
* @param file
* @return
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static String createDigest(File file) throws NoSuchAlgorithmException,
IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(file);
try {
byte[] buff = new byte[256];
int len = 0;
while ((len = in.read(buff, 0, buff.length)) >= 0) {
md.update(buff, 0, len);
}
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw e;
}
}
}
return convertString(md.digest());
}
/**
*
* @param digest
* @return
*/
private static String convertString(byte[] digest) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
sb.append(HEX_CHARS[(digest[i] & 0xf0) >> 4]);
sb.append(HEX_CHARS[digest[i] & 0x0f]);
}
return sb.toString();
}


