hash - Strange loop when using DigestInputStream in Java -
the following code supposed compute hash string in text file using digestinputstream class in java.
import java.io.*; import java.security.*; public class returndigest extends thread { private file input; private byte[] digest; public returndigest(file input) { this.input = input; } public void run() { try { fileinputstream in = new fileinputstream(input); messagedigest sha = messagedigest.getinstance("sha"); digestinputstream din = new digestinputstream(in, sha); int b; while ((b = din.read()) != -1) ; din.close(); digest = sha.digest(); } catch (ioexception ex) { system.err.println(ex); } catch (nosuchalgorithmexception ex) { system.err.println(ex); } } public byte[] getdigest() { return digest; } } my question is: why there semicolon after while statement? correct? when remove it, error. have not ever heard possible put semicolon after while statement. can clarify case in code please.
it's empty loop, nothing done value read. in fact 1 rid of variable b altogether:
while (din.read() != -1) { } i replaced semicolon (empty statement) empty block, that's more explicit happens here.
this atypical way read input stream (usually want do data read), because digest input stream has side-effect: if read it also computes hash of whatever read. if only want hash, need read, don't need values read.
Comments
Post a Comment