The following code supposed to compute the hash for a string in a 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 is a semicolon after the while
statement? Is this correct? When I remove it, I get error. I have not ever heard that it is possible to put a semicolon after a while statement. Can you clarify the case in this code please.
It's an empty loop, nothing is done with the value read. In fact one could get rid of the variable b
altogether:
while (din.read() != -1) {
}
I also replaced the semicolon (empty statement) with an empty block, as that's slightly more explicit about what happens here.
This is a very atypical way to read from an input stream (usually you want to do something with the data that was read), because the digest input stream has a side-effect: if you read from it it also computes the hash of whatever is read. If you only want the hash, you need to read, but don't need to do anything with the values that where read.
It is correct.
while ((b = din.read()) != -1) ;
din.close();
The While
loop will only exit when din.read() is not -1, when there's nothing more to read. Then and just then will close it.
So you can see it:
while ((b = din.read()) != -1) ;
and
while ((b = din.read()) != -1)
{ }
Are equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With