What is the best way to create a SHA-1 for a very large file in pure Java6? How to implement this method:
public abstract String createSha1(java.io.File file);
Use the MessageDigest
class and supply data piece by piece. The example below ignores details like turning byte[] into string and closing the file, but should give you the general idea.
public byte[] createSha1(File file) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
InputStream fis = new FileInputStream(file);
int n = 0;
byte[] buffer = new byte[8192];
while (n != -1) {
n = fis.read(buffer);
if (n > 0) {
digest.update(buffer, 0, n);
}
}
return digest.digest();
}