당신은 크기
당신이 스트림을 읽는 동안 당신은 당신의 MD5를 계산할 수를 제출하지, MD5로 확인해야합니다.
파일을 저장 한 후, 당신은 다시 MD5를 생성하고
UPDATE를 비교할 수 있습니다, 그리고
https://stackoverflow.com/a/304350/3230038을 참조하십시오 - 여기에 대한 내 더 자세한 생각입니다. 나는 전체 byte []를 메모리에 가져 오지 않고 MD5를 계산하기를 원한다고 가정하고 있습니다. 이 경우, 나는 (당신이 리눅스에 있다면 당신은 그냥 md5sum이 사용할 수 있습니다) 다시 MD5를 확인, 당신은 저장 한 후 다음 저장하고 당신이, 즉석에서이 옵션
- 계산 MD5를 생각
- 첫 번째 패스에서 MD5를 계산 한 다음 두 번째 패스에서 파일을 저장합니다.예를 들어
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
public class MD5OnTheFly {
/**
* @param args
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
long ini = System.currentTimeMillis();
File file = new File("/home/leoks/Downloads/VirtualBox-4.3.0.tar");
System.out.println("size:"+file.length());
InputStream is = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
DigestInputStream dis = new DigestInputStream(is, md);
IOUtils.copy(dis, new NullOutputStream());
byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(0xff & digest[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
System.out.println(hexString);
long end = System.currentTimeMillis();
System.out.println(end-ini+" millis");
}
}
반환
410859520
dda81aea75a83b1489662c6bcd0677e4
1413 millis
다음
[[email protected] ~]$ md5sum /home/leoks/Downloads/VirtualBox-4.3.0.tar
dda81aea75a83b1489662c6bcd0677e4 /home/leoks/Downloads/VirtualBox-4.3.0.tar
[[email protected] ~]$
출처
2014-02-05 14:08:49
Leo
파일 스트림을 읽는 동안 MD5를 계산하고 저장 후 다시 확인하는 방법은 무엇입니까? 이런 식으로 http://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java – Leo
MD5를 계산하는 동안 문제가 발생하면 결과 파일의 내용을 알 수 없습니다. 디스크에 기록 된 내용이 유효한지 여부. – Genjuro
MD5를 계산하는 데 문제가 있으면 파일을 다시 작성해야한다고 가정합니다. (최대 재시도 횟수를 잊지 말것) – Leo