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.

public class DirectDeflater {<br />

}<br />

public final static String DEFLATE_SUFFIX = ".dfl";<br />

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

}<br />

Deflater def = new Deflater();<br />

byte[] input = new byte[1024];<br />

byte[] output = new byte[1024];<br />

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

}<br />

try {<br />

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

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

DEFLATE_SUFFIX);<br />

while (true) { // read and deflate the data<br />

// Fill the input array.<br />

int numRead = fin.read(input);<br />

if (numRead == -1) { // end of stream<br />

// Deflate any data that remains in the input buffer.<br />

def.finish();<br />

while (!def.finished()) {<br />

int numCompressedBytes = def.deflate(output, 0,<br />

output.length);<br />

if (numCompressedBytes > 0) {<br />

fout.write(output, 0, numCompressedBytes);<br />

} // end if<br />

} // end while<br />

break; // Exit while loop.<br />

} // end if<br />

else { // Deflate the input.<br />

def.setInput(input, 0, numRead);<br />

while (!def.needsInput()) {<br />

int numCompressedBytes = def.deflate(output, 0,<br />

output.length);<br />

if (numCompressedBytes > 0) {<br />

fout.write(output, 0, numCompressedBytes);<br />

} // end if<br />

} // end while<br />

} // end else<br />

} // end while<br />

fin.close();<br />

fout.flush();<br />

fout.close();<br />

def.reset();<br />

} // end try<br />

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

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

This program is more complicated than it needs to be, because it has to read the file in small<br />

chunks. In Example 9.3, later in this chapter, you'll see a simpler program that achieves the<br />

same result using the DeflaterOutputStream class.<br />

147

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

Saved successfully!

Ooh no, something went wrong!