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

The first method fills the specified output array with the bytes of compressed data. The<br />

second fills the specified subarray of output beginning at offset and continuing for length<br />

bytes with the compressed data. Both methods return the actual number of compressed bytes<br />

written into the array. You do not know in advance how many compressed bytes will actually<br />

be written into output, because you do not know how well the data will compress. You<br />

always have to check the return value. If deflate() returns 0, you should check<br />

needsInput() to see if you need to call setInput() again to provide more uncompressed<br />

input data:<br />

public boolean needsInput()<br />

When more data is needed, the needsInput() method returns true. At this point you should<br />

invoke setInput() again to feed in more uncompressed input data, call deflate(), and<br />

repeat the process until deflate() returns and there is no more input data to be compressed.<br />

9.1.1.7 Finish the deflation<br />

Finally, when the input data is exhausted, invoke finish() to indicate that no more data is<br />

forthcoming and the deflater should finish with the data it already has in its buffer:<br />

public synchronized void finish()<br />

The finished() method returns true when the end of the compressed output has been<br />

reached; that is, when all data stored in the input buffer has been deflated:<br />

public synchronized boolean finished()<br />

After calling finish(), you invoke deflate() repeatedly until finished() returns true.<br />

This flushes out any data that remains in the input buffer.<br />

9.1.1.8 Reset the deflater and start over<br />

This completes the sequence of method invocations required to compress data. If you'd like to<br />

use the same strategy, compression level, and other settings to compress more data with the<br />

same Deflater, call its reset() method:<br />

public native synchronized void reset()<br />

Otherwise, call end() to throw away any unprocessed input and free the resources used by the<br />

native code:<br />

public native synchronized void end()<br />

The finalize() method calls end() before the deflater is garbage-collected, if you forget:<br />

protected void finalize()<br />

9.1.1.9 An example<br />

Example 9.1 is a simple program that deflates files named on the command line. First<br />

a Deflater object, def, is created with the default strategy, method, and compression level.<br />

145

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

Saved successfully!

Ooh no, something went wrong!