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.

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

This writes all remaining data in the buffer onto the underlying output stream. Then it writes a<br />

trailer containing a CRC value and the number of uncompressed bytes stored in the file onto<br />

the stream. This trailer is part of the gzip format specification that's not part of a raw deflated<br />

file. If you're through with the underlying stream as well as the gzip output stream, call<br />

close() instead of finish(). If the stream hasn't yet been finished, close() finishes it, then<br />

closes the underlying output stream. From this point on, data may not be written to that<br />

stream.<br />

public void close() throws <strong>IO</strong>Exception<br />

Example 9.5 is a simple command-line program that reads a list of files from the command<br />

line and gzips each one. A file input stream is used to read each file. A file output stream<br />

chained to a gzip output stream is used to write each output file. The gzipped files have the<br />

same name as the input files plus the suffix .gz.<br />

Example 9.5. The GZipper<br />

import java.io.*;<br />

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

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

public class GZipper {<br />

}<br />

public final static String GZIP_SUFFIX = ".gz";<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 />

FileOutputStream fout = new FileOutputStream(args[i] +<br />

GZIP_SUFFIX);<br />

GZIPOutputStream gzout = new GZIPOutputStream(fout);<br />

StreamCopier.copy(fin, gzout);<br />

gzout.close();<br />

}<br />

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

}<br />

If this looks similar to Example 9.3, that's because it is. All that's changed is the compression<br />

format (gzip instead of deflate) and the compressed file suffix. However, since gzip and<br />

gunzip are available on virtually all operating systems— unlike raw deflate—you can test this<br />

code by unzipping the files it produces with the Free Software Foundation's (FSF) gunzip or<br />

some other program that handles gzipped files.<br />

9.2.4 The GZIPInputStream Class<br />

The java.util.zip.GZIPInputStream class is a subclass of InflaterInputStream that<br />

provides a very simple interface for decompressing gzipped data:<br />

public class GZIPInputStream extends InflaterInputStream<br />

There are two constructors in this class:<br />

157

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

Saved successfully!

Ooh no, something went wrong!