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.

9.3.3.6 An example<br />

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

Example 9.11 is an alternative unzipper that uses a ZipInputStream instead of a ZipFile.<br />

There's not really a huge advantage to using one or the other. Use whichever you find more<br />

convenient or aesthetically pleasing.<br />

Example 9.11. Another Unzipper<br />

import java.util.*;<br />

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

import java.io.*;<br />

import com.macfaq.io.*;<br />

public class Unzipper2 {<br />

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

ZipInputStream zin = new ZipInputStream(fin);<br />

ZipEntry ze = null;<br />

while ((ze = zin.getNextEntry()) != null) {<br />

System.out.println("Unzipping " + ze.getName());<br />

FileOutputStream fout = new FileOutputStream(ze.getName());<br />

StreamCopier.copy(zin, fout);<br />

zin.closeEntry();<br />

fout.close();<br />

}<br />

zin.close();<br />

}<br />

catch (<strong>IO</strong>Exception e) {<br />

System.err.println(e);<br />

e.printStackTrace();<br />

}<br />

}<br />

9.4 Checksums<br />

Compressed files are especially susceptible to corruption. While changing a bit from to 1 or<br />

vice versa in a text file generally only affects a single character, changing a single bit in a<br />

compressed file often makes the entire file unreadable. Therefore, it's customary to store a<br />

checksum with the compressed file so that the recipient can verify that the file is intact. The<br />

zip format does this automatically, but you may wish to use manual checksums in other<br />

circumstances as well.<br />

There are many different checksum schemes. A particularly simple example adds a parity bit<br />

to the data, typically 1 if the number of 1 bits is odd, if the number of 1 bits is even. This<br />

checksum can be calculated by summing up the number of 1 bits and taking the remainder<br />

when that sum is divided by two. However, this scheme isn't very robust. It can detect singlebit<br />

errors, but in the face of bursts of errors as often occur in transmissions over modems and<br />

other noisy connections, there's a 50/50 chance that corrupt data will be reported as correct.<br />

172

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

Saved successfully!

Ooh no, something went wrong!