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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

public void setMessageDigest(MessageDigest digest)<br />

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

public MessageDigest getMessageDigest()<br />

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

After you invoke getMessageDigest(), the digest field contains the digest of all the data<br />

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

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

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

md.digest();<br />

On rare occasions, you may only want to digest part of a stream. For instance, you might want<br />

to calculate the digest of the body of an email message while ignoring the headers. You can<br />

turn digesting off at 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 output streams are<br />

created, they are on by default.<br />

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

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

public String toString()<br />

Example 10.3 is a FileDigestOutputStream class that reads data from a specified URL and<br />

copies it into a file on the local system. As the file is written, its SHA digest is calculated.<br />

When the file is closed, the digest is printed.<br />

Example 10.3. FileDigestOutputStream<br />

import java.net.*;<br />

import java.io.*;<br />

import java.security.*;<br />

public class FileDigest {<br />

public static void main(String[] args) {<br />

if (args.length != 2) {<br />

System.err.println("Usage: java FileDigest url filename");<br />

return;<br />

}<br />

try {<br />

URL u = new URL(args[0]);<br />

FileOutputStream out = new FileOutputStream(args[1]);<br />

copyFileWithDigest(u.openStream(), out);<br />

out.close();<br />

}<br />

catch (MalformedURLException e) {<br />

System.err.println(args[0] + " is not a URL");<br />

}<br />

206

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

Saved successfully!

Ooh no, something went wrong!