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.

9.3.3 The ZipInputStream Class<br />

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

Zip input streams read data from zip archives, which are most commonly stored in files. As<br />

with output streams, it's generally best not to read the raw data. (If you must read the raw<br />

data, you can always use a bare file input stream.) Instead, the input is first parsed into zip<br />

entries. Once you've positioned the stream on a particular zip entry, you read decompressed<br />

data from it using the normal read() methods. Then the entry is closed, and you open the<br />

next zip entry in the file. The sequence of steps you must follow to read data from a zip input<br />

stream is as follows:<br />

1. Construct a ZipInputStream object from an underlying stream, most commonly a file<br />

input stream.<br />

2. Open the next zip entry in the archive.<br />

3. Read data from the zip entry using InputStream methods like read().<br />

4. Close the zip entry (optional).<br />

5. Repeat steps 2 through 4 as long as there are more entries (files) remaining in the<br />

archive.<br />

6. Close the zip input stream.<br />

Steps 2 and 4, the opening and closing of zip entries in the archive, are new; you won't find<br />

anything like them in other input stream classes. However, attempts to read data from a zip<br />

input stream using only the regular read(), skip(), and close() methods without first<br />

opening a zip entry are doomed to failure.<br />

You probably noticed that the ZipInputStream class provides a second<br />

way to decompress zip files. The ZipFile class approach shown in the<br />

Unzipper program of Example 9.8 is the first. ZipInputStream uses<br />

one input stream to read from successive entries. The ZipFile class<br />

uses different input stream objects for different entries. Which to use is<br />

mainly a matter of aesthetics. There's not a strong reason to prefer one<br />

approach over the other, though the ZipInputStream is somewhat more<br />

convenient in the middle of a sequence of filters.<br />

9.3.3.1 Construct a ZipInputStream<br />

There is a single ZipInputStream() constructor that takes as an argument the underlying<br />

input stream:<br />

public ZipInputStream(InputStream in)<br />

For example:<br />

FileInputStream fin = new FileInputStream("data.zip");<br />

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

No further initialization or parameter setting are needed. A zip input stream can read from a<br />

file regardless of the compression method or level used.<br />

170

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

Saved successfully!

Ooh no, something went wrong!