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

The ZipFile class contains two constructors. The first takes a filename as an argument. The<br />

second takes a java.io.File object as an argument. File objects will be discussed in<br />

Chapter 12 ; for now, I'll just use the constructor that accepts a filename. Functionally, these<br />

two constructors are similar.<br />

public ZipFile(String filename) throws <strong>IO</strong>Exception<br />

public ZipFile(File file) throws ZipException, <strong>IO</strong>Exception<br />

ZipException is a subclass of <strong>IO</strong>Exception that generally indicates that data in the zip file<br />

doesn't fit the zip format. In this case, the zip exception's message will contain more details,<br />

like "invalid END header signature" or "cannot have more than one drive." While these may<br />

be useful to a zip expert, in general they indicate that the file is corrupted, and there's not<br />

much that can be done about it.<br />

public class ZipException extends <strong>IO</strong>Exception<br />

I can discern no reason why the first constructor is declared to throw <strong>IO</strong>Exception, while the<br />

second is declared to throw both <strong>IO</strong>Exception and ZipException. The second constructor<br />

merely invokes the first after converting the File object to a string pathname. Since<br />

ZipException extends <strong>IO</strong>Exception, your code can catch either ZipException and<br />

<strong>IO</strong>Exception or just <strong>IO</strong>Exception, as your needs dictate.<br />

Both constructors attempt to open the specified file for random access. If the file is opened<br />

successfully with no exceptions, the entries() method will return a list of all the files in the<br />

archive:<br />

public Enumeration entries()<br />

The return value is a java.util.Enumeration object containing one<br />

java.util.zip.ZipEntry object for each file in the archive. Example 9.7 lists the entries in<br />

a zip file specified on the command line. The toString() method is used implicitly to<br />

provide the name for each zip entry in the list.<br />

Example 9.7. ZipLister<br />

import java.util.*;<br />

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

import java.io.*;<br />

public class ZipLister {<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 />

while (e.hasMoreElements()) {<br />

System.out.println(e.nextElement());<br />

}<br />

}<br />

160

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

Saved successfully!

Ooh no, something went wrong!