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 files to be stored in the archive are read from the command line. An optional -d<br />

command-line flag can be used to set the level of compression from 0 to 9.<br />

Example 9.10. The Zipper Program<br />

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

import java.io.*;<br />

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

public class Zipper {<br />

}<br />

}<br />

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

if (args.length < 2) {<br />

System.out.println("Usage: java Zipper [-d level] name.zip"+<br />

" file1 file2...");<br />

return;<br />

}<br />

String outputFile = args[0];<br />

// Maximum compression is our default.<br />

int level = 9;<br />

int start = 1;<br />

if (args[0].equals("-d")) {<br />

try {<br />

level = Integer.parseInt(args[1]);<br />

outputFile = args[2];<br />

start = 3;<br />

}<br />

catch (Exception e) {<br />

System.out.println("Usage: java Zipper [-d level] name.zip"<br />

" file1 file2...");<br />

return;<br />

}<br />

}<br />

try {<br />

FileOutputStream fout = new FileOutputStream(outputFile);<br />

ZipOutputStream zout = new ZipOutputStream(fout);<br />

zout.setLevel(level);<br />

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

ZipEntry ze = new ZipEntry(args[i]);<br />

try {<br />

System.out.println("Compressing " + args[i]);<br />

FileInputStream fin = new FileInputStream(args[i]);<br />

zout.putNextEntry(ze);<br />

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

zout.closeEntry();<br />

fin.close();<br />

}<br />

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

}<br />

zout.close();<br />

}<br />

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

169

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

Saved successfully!

Ooh no, something went wrong!