Here are my two code snippets:
public class Uploader {
private static final String SHA_256 = "SHA-256";
public String getFileSHA2Checksum(InputStream fis) throws IOException {
try {
MessageDigest md5Digest = MessageDigest.getInstance(SHA_256);
return getFileChecksum(md5Digest, fis);
} catch (NoSuchAlgorithmException e) {
return "KO";
}
}
public void transferTo(InputStream fis) throws IOException {
FileUtils.copyInputStreamToFile(fis, file2);
}
My code uses this class as:
Is it possible to copyToFile and calculateChecksum at the same time leveraging InputStream is open?
You can use the
DigestInputStreamto calculate a hash while reading from a stream. That is, you wrap the original input stream with aDigestInputStreamand read through theDigestInputStream. While reading the data, the message digest is automatically updated, and you can retrieve the digest after you read the entire stream.Alternatively, you can use
DigestOutputStreamto calculate a hash while writing to a stream. In a similar vein, you wrap the destination output stream with aDigestOutputStreamand write through theDigestOutputStream.A quick and dirty example:
In terms of your existing code, you could do something like:
(NOTE:
HexFormatwas introduced in Java 17, if you're using an earlier version, you'll need an alternative.)