Java Reference
In-Depth Information
public InstanceCallbackDigest ( String filename ,
InstanceCallbackDigestUserInterface callback ) {
this . filename = filename ;
this . callback = callback ;
}
@Override
public void run () {
try {
FileInputStream in = new FileInputStream ( filename );
MessageDigest sha = MessageDigest . getInstance ( "SHA-256" );
DigestInputStream din = new DigestInputStream ( in , sha );
while ( din . read () != - 1 ) ; // read entire file
din . close ();
byte [] digest = sha . digest ();
callback . receiveDigest ( digest );
} catch ( IOException | NoSuchAlgorithmException ex ) {
System . err . println ( ex );
}
}
}
The InstanceCallbackDigestUserInterface class shown in Example 3-8 holds the
main() method as well as the receiveDigest() method used to handle an incoming
digest. Example 3-8 just prints out the digest, but a more expansive class could do other
things as well, such as storing the digest in a field, using it to start another thread, or
performing further calculations on it.
Example 3-8. InstanceCallbackDigestUserInterface
import javax.xml.bind.* ; // for DatatypeConverter; requires Java 6 or JAXB 1.0
public class InstanceCallbackDigestUserInterface {
private String filename ;
private byte [] digest ;
public InstanceCallbackDigestUserInterface ( String filename ) {
this . filename = filename ;
}
public void calculateDigest () {
InstanceCallbackDigest cb = new InstanceCallbackDigest ( filename , this );
Thread t = new Thread ( cb );
t . start ();
}
void receiveDigest ( byte [] digest ) {
this . digest = digest ;
System . out . println ( this );
}
Search WWH ::




Custom Search