Strange loop when using DigestInputStream in Java

The following code should calculate the hash for a string in a text file using the 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 is there a semicolon after the while statement? It's right? When I delete it, I get an error. I have never heard that you can put a semicolon after some time. Can you clarify the situation in this code, please.

+4
source share
2 answers

This is an empty loop; nothing is done when reading the value. In fact, you can completely get rid of the variable b :

 while (din.read() != -1) { } 

I also replaced the semicolon (empty statement) with an empty block, as this is a bit more detailed on what is going on here.

This is a very atypical way of reading from the input stream (usually you want to do something with the data that has been read), since the digest input stream has a side effect: if you read it, it also calculates the hash of everything that is read. If you only need a hash, you need to read, but you don't need to do anything with the values ​​that are read.

+3
source

It is right.

 while ((b = din.read()) != -1) ; din.close(); 

While loop will be completed only when din.read () is not -1, when there is nothing more to read. Then and immediately closes it.

So you can see it:

 while ((b = din.read()) != -1) ; 

and

 while ((b = din.read()) != -1) { } 

are equal.

+1
source

Source: https://habr.com/ru/post/1480917/


All Articles