Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange loop when using DigestInputStream in Java

Tags:

java

hash

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.

like image 853
user2192774 Avatar asked May 15 '13 10:05

user2192774


2 Answers

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.

like image 88
Joachim Sauer Avatar answered Nov 01 '22 09:11

Joachim Sauer


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.

like image 23
aran Avatar answered Nov 01 '22 08:11

aran