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 />

public long getValue() {<br />

return checksum;<br />

}<br />

public void reset() {<br />

checksum = 0;<br />

}<br />

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

The java.util.zip package provides two concrete implementations of the Checksum<br />

interface, CRC32 and Adler32. Both produce 32-bit checksums. The Adler-32 algorithm is not<br />

quite as reliable as CRC-32 but can be computed much faster. Both of these classes have a<br />

single no-argument constructor:<br />

public CRC32()<br />

public Adler32()<br />

They share the same five methods, four implementing the methods of the Checksum interface,<br />

plus one additional update() method that reads an entire byte array:<br />

public void update(int b)<br />

public native void update(byte[] data, int offset, int length)<br />

public void update(byte[] data)<br />

public void reset()<br />

public long getValue()<br />

Example 9.13, FileSummer, is a simple program that calculates and prints a CRC-32<br />

checksum for any file. However, it's structured such that the static getCRC32() method can<br />

calculate a CRC-32 checksum for any stream.<br />

Example 9.13. FileSummer<br />

import java.io.*;<br />

import java.util.zip.*;<br />

public class FileSummer {<br />

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

}<br />

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

try {<br />

FileInputStream fin = new FileInputStream(args[i]);<br />

System.out.println(args[i] + ":\t" + getCRC32(fin));<br />

fin.close();<br />

}<br />

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

}<br />

public static long getCRC32(InputStream in) throws <strong>IO</strong>Exception {<br />

Checksum cs = new CRC32();<br />

// It would be more efficient to read chunks of data<br />

// at a time, but this is simpler and easier to understand.<br />

174

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

Saved successfully!

Ooh no, something went wrong!