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.1.2.7 An example<br />

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

Example 9.2 is a simple program that inflates files named on the command line. First an<br />

Inflater object, inf, is created. A file input stream named fin is opened to each file. At the<br />

same time, a file output stream named fout is opened to an output file with the same name<br />

minus the three-letter extension .df l. The program then enters a loop in which it tries to read<br />

1024 -byte chunks of data from fin , though care is taken not to assume that 1024 bytes are<br />

actually read. Any data that is successfully read is passed to the inflater's setInput()<br />

method. This data is repeatedly inflated and written onto the output stream until the inflater<br />

indicates that it needs more input. Then the process repeats itself until the end of the input<br />

stream is reached and the inflater's finished() method returns true. At this point, the<br />

program breaks out of the read() loop and moves on to the next file.<br />

Example 9.2. The DirectInflater<br />

import java.io.*;<br />

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

public class DirectInflater {<br />

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

Inflater inf = new Inflater();<br />

byte[] input = new byte[1024];<br />

byte[] output = new byte[1024];<br />

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

try {<br />

if (!args[i].endsWith(DirectDeflater.DEFLATE_SUFFIX)) {<br />

System.err.println(args[i] + " does not look like a deflated<br />

file");<br />

continue;<br />

}<br />

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

FileOutputStream fout = new FileOutputStream(args[i].substring(0,<br />

args[i].length() - DirectDeflater.DEFLATE_SUFFIX.length()));<br />

while (true) { // Read and inflate the data.<br />

// Fill the input array.<br />

int numRead = fin.read(input);<br />

if (numRead != -1) { // End of stream, finish inflating.<br />

inf.setInput(input, 0, numRead);<br />

} // end if<br />

// Inflate the input.<br />

int numDecompressed = 0;<br />

while ((numDecompressed = inf.inflate(output, 0, output.length))<br />

!= 0) {<br />

fout.write(output, 0, numDecompressed);<br />

}<br />

// At this point inflate() has returned 0.<br />

// Let's find out why.<br />

if (inf.finished()) { // all done<br />

break;<br />

}<br />

else if (inf.needsDictionary()) { //We don't handle dictionaries.<br />

151

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

Saved successfully!

Ooh no, something went wrong!