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.

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

A file input stream named fin is opened to each file. At the same time, a file output stream<br />

named fout is opened to an output file with the same name plus the three-letter extension .dfl.<br />

The program then enters a loop in which it tries to read 1024 -byte chunks of data from fin,<br />

though care is taken not to assume that 1024 bytes are actually read. Any data that is<br />

successfully read is passed to the deflater's setInput() method. The data is repeatedly<br />

deflated and written onto the output stream until the deflater indicates that it needs more<br />

input. Then the process repeats itself until the end of the input stream is reached. When no<br />

more input is available, the deflater's finish() method is called. Then the deflater's<br />

deflate() method is repeatedly invoked until its finished() method returns true. At this<br />

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

Figure 9.2 is a flow chart demonstrating this sequence for a single file. One thing may seem<br />

a little fishy about this chart. After the deflater is finished, a repeated check is made to see if<br />

the deflater is in fact finished. The finish() method tells the deflater that no more data is<br />

forthcoming and it should work with whatever data remains in its input buffer. However,<br />

the finished() method does not actually return true until the input buffer has been emptied<br />

by calls to deflate().<br />

Figure 9.2. The deflation sequence<br />

Example 9.1. The DirectDeflater<br />

import java.io.*;<br />

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

146

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

Saved successfully!

Ooh no, something went wrong!