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.

}<br />

}<br />

catch (MalformedURLException e) {System.err.println(e);}<br />

catch (Exception e) {System.err.println(e);}<br />

public static byte[] getDigestFromURL(URL u)<br />

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

}<br />

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

InputStream in = u.openStream();<br />

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

while (true) {<br />

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

if (bytesRead < 0) { // end of stream<br />

break;<br />

}<br />

sha.update(data, 0, bytesRead);<br />

}<br />

return sha.digest();<br />

Here's a sample run:<br />

% java TrueMirror http://metalab.unc.edu/javafaq/<br />

http://sunsite.uakom.sk/javafaq/<br />

http://metalab.uakom.sk/javafaq/ is up to date<br />

10.2.7 Accessor Methods<br />

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

The MessageDigest class contains three accessor methods that return information about the<br />

digest:<br />

public final Provider getProvider()<br />

public final String getAlgorithm()<br />

public final int getDigestLength()<br />

The getProvider() method returns a reference to the instance of java.security.Provider<br />

that provided this MessageDigest implementation. The getAlgorithm() method returns a<br />

string containing the name of the digest algorithm as given in Table 10.1; for example, "SHA"<br />

or "MD2". Finally, getDigestLength()returns the length of the digest in bytes. Digest<br />

algorithms are supposed to have fixed lengths. For instance, SHA digests are always 20 bytes<br />

long. However, this method allows for the possibility of variable length digests. It returns if<br />

the length of the digest is not yet available.<br />

10.2.8 Cloning Digests<br />

Some digests allow themselves to be cloned, though not all do. A digest that does not<br />

implement cloning throws a CloneNotSupportedException if you attempt to clone it. SHA<br />

and MD5 digests from the JDK do support cloning. Cloning a digest is useful if you want to<br />

view a series of intermediate digests before the entire data sequence has been read:<br />

public Object clone() throws CloneNotSupportedException<br />

202

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

Saved successfully!

Ooh no, something went wrong!