23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

For example:<br />

URL u = new URL("http://java.sun.com");<br />

DigestInputStream din = new DigestInputStream(u.openStream(),<br />

MessageDigest.getInstance("SHA"));<br />

<strong>Java</strong> I/O<br />

The digest is not cloned inside the class. Only a reference to it is stored. Therefore, the<br />

message digest used inside the stream should only be used by the stream. Simultaneous or<br />

interleaved use by other objects will corrupt the digest.<br />

You can change the MessageDigest object used by the stream with the<br />

setMessageDigest() method:<br />

public void setMessageDigest(MessageDigest digest)<br />

You can retrieve the message digest at any time by calling getMessageDigest():<br />

public MessageDigest getMessageDigest()<br />

After you invoke getMessageDigest(), the digest field of the stream has received all the<br />

data read by the stream up to that point. However, it has not been finished. It is still necessary<br />

to invoke digest() to complete the calculation. For example:<br />

MessageDigest md = dis.getMessageDigest();<br />

md.digest();<br />

On rare occasion, you may only want to digest part of a stream. You can turn digesting off at<br />

any point by passing false to the on() method:<br />

public void on(boolean on)<br />

You can turn digesting back on by passing true to on(). When digest streams are created,<br />

they are on by default.<br />

Finally, there's a toString() method, which is a little unusual in input streams. It simply<br />

returns "[Digest Input Stream]" plus the string representation of the digest.<br />

public String toString()<br />

Here's a revised printDigest() method for Example 10.1 that makes use of a<br />

DigestInputStream :<br />

public static void printDigest(InputStream in)<br />

throws <strong>IO</strong>Exception, NoSuchAlgorithmException {<br />

MessageDigest sha = MessageDigest.getInstance("SHA");<br />

DigestInputStream din = new DigestInputStream(in, sha);<br />

byte[] data = new byte[128];<br />

while (true) {<br />

int bytesRead = din.read(data);<br />

if (bytesRead < 0) break;<br />

}<br />

MessageDigest md = din.getMessageDigest();<br />

204

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!