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.

}<br />

byte[] result = md.digest();<br />

for (int i = 0; i < result.length; i++) {<br />

System.out.println(result[i]);<br />

}<br />

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

The main purpose of DigestInputStream is to be one of a chain of filters. Otherwise, it<br />

doesn't really make your work any easier. You still need to construct the MessageDigest<br />

object by invoking getInstance(), pass it to the DigestInputStream() constructor,<br />

retrieve the MessageDigest object from the input stream, invoke its digest() method, and<br />

retrieve the digest data from that object. I would prefer the DigestInputStream to<br />

completely hide the MessageDigest object. You could pass the name of the digest algorithm<br />

to the constructor as a string rather than an actual MessageDigest object. The digest would<br />

only be made available after the stream was closed, and then only through its data, not<br />

through the actual object.<br />

10.3.2 DigestOutputStream<br />

The DigestOutputStream class is a subclass of FilterOutputStream that maintains a digest<br />

of all the bytes it has written:<br />

public class DigestOutputStream extends FilterOutputStream<br />

DigestOutputStream has all the usual methods of any output stream, like write(),<br />

flush(), and close(). It overrides two write() methods to do its filtering:<br />

public void write(int b) throws <strong>IO</strong>Exception<br />

public void write(byte[] data, int offset, int length) throws <strong>IO</strong>Exception<br />

These are used much as they would be for any other output stream. DigestOutputStream<br />

does not change the data it writes in any way. However, as each byte or group of bytes is<br />

written, it is fed as input to a MessageDigest object stored in the class as the protected<br />

digest field:<br />

protected MessageDigest digest;<br />

This is normally set in the constructor:<br />

public DigestOutputStream(OutputStream out, MessageDigest digest)<br />

For example:<br />

FileOutputStream fout = new FileOutputStream("data.txt");<br />

DigestOutputStream dout = new DigestOutputStream(fout,<br />

MessageDigest.getInstance("SHA"));<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. Interleaved use by<br />

other objects or simultaneous use by other threads will corrupt the digest. You can change the<br />

MessageDigest object used by the stream with the setMessageDigest() method:<br />

205

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

Saved successfully!

Ooh no, something went wrong!