출처 바로가기
파일의 무결성 검사를 할 때 해시값을 이용한 비교를 많이 사용합니다. 이 예제는 단순히 파일이 같은지 여부 체크에만 사용할 것이기 때문에 복잡한 알고리즘은 필요하지 않고 MD5 정도의 해시 알고리즘이면 충분합니다.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public FileManager {
public static String getHash(String path) throws IOException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
FileInputStream fileInputStream = new FileInputStream(path);
byte[] dataBytes = new byte[1024];
Integer nRead = 0;
while((nRead = fileInputStream.read(dataBytes)) != -1) {
messageDigest.update(dataBytes, 0, nRead);
}
byte[] mdBytes = messageDigest.digest();
StringBuffer stringBuffer = new StringBuffer();
for(Integer i = 0; i < mdBytes.length; i++) {
stringBuffer.append(Integer.toString((mdBytes[i] & 0xff) + 0x100, 16)).substring(1);
}
return stringBuffer.toString();
}
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
String filePath = "/Users/example/Documents/midi/canyon.mid";
System.out.println(FileManager.getHash(filePath));
}
}





0개의 댓글