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.

}<br />

}<br />

}<br />

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

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

Here are the first few lines that result from running this program on the classes.zip file from<br />

JDK 1.1.4:<br />

% java ZipLister /usr/local/java/lib/classes.zip<br />

sun/net/www/protocol/systemresource/ParseSystemURL.class<br />

java/io/ObjectInputValidation.class<br />

sun/awt/motif/MTextFieldPeer.class<br />

sun/tools/javac/BatchParser.class<br />

sun/rmi/transport/proxy/HttpOutputStream.class<br />

To get a single entry in the zip file rather than a list of the entire contents, you pass the name<br />

of the entry to the getEntry() method:<br />

public ZipEntry getEntry(String name)<br />

Of course, this requires you to know the name of the entry in advance. The name is simply the<br />

path and filename, like java/io/ObjectInputValidation.class. For example, to retrieve the zip<br />

entry for java/io/ObjectInputValidation.class from the ZipFile zf, you might write:<br />

ZipEntry ze = zf.getEntry("java/io/ObjectInputValidation.class");<br />

You can also get the name with the getName() method of the ZipEntry class, discussed later<br />

in this chapter. This method, however, requires you to have a ZipEntry object already, so<br />

there's a little chicken-and-egg problem here.<br />

Most of the time, you'll want more than the names of the files in the archive. You can get the<br />

actual contents of the zip entry using getInputStream():<br />

public InputStream getInputStream(ZipEntry ze) throws <strong>IO</strong>Exception<br />

This returns an input stream from which you can read the uncompressed contents of the zip<br />

entry (file). Example 9.8 is a simple unzip program that uses this input stream to unpack zip<br />

archives named on the command line.<br />

Example 9.8. Unzipper<br />

import java.util.*;<br />

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

import java.io.*;<br />

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

public class Unzipper {<br />

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

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

try {<br />

ZipFile zf = new ZipFile(args[i]);<br />

Enumeration e = zf.entries();<br />

161

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

Saved successfully!

Ooh no, something went wrong!