Java Reference
In-Depth Information
Example 3−4: FileLister.java (continued)
// Arrange for the application to exit when the window is closed
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) { System.exit(0); }
});
// Finally, pop the window up up.
f.show();
}
}
Compressing Files and Directories
Example 3-5 demonstrates an interesting application of stream classes: compress-
ing files and directories. The classes of interest in this example are not actually
part of the java.io package, but instead part of the java.util.zip package. The
Compress class defines two static methods, gzipFile() , which compresses a file
using GZIP compression format, and zipDirectory() , which compresses the files
(but not directories) in a directory using the ZIP archive and compression format.
gzipFile() uses the GZIPOutputStream class, while zipDirectory() uses the
ZipOutputStream and ZipEntry classes, all from java.util.zip .
This example demonstrates the versatility of the stream classes and shows again
how streams can be wrapped around one another so that the output of one stream
becomes the input of another. This technique makes it possible to achieve a great
variety of effects. Notice again the while loop in both methods that does the actual
copying of data from source file to compressed file. These methods do not attempt
to handle exceptions; instead they just pass them on to the caller, which is often
exactly the right thing to do.
Compress is meant to be used as a utility class by other programs, so it doesn't
itself include a main() method. The example does include an inner Compress.Test
class, however, which has a main() method that can test the gzipFile() and
zipDirectory() methods.
Example 3−5: Compress.java
package com.davidflanagan.examples.io;
import java.io.*;
import java.util.zip.*;
/**
* This class defines two static methods for gzipping files and zipping
* directories. It also defines a demonstration program as a nested class.
**/
public class Compress {
/** Gzip the contents of the from file and save in the to file. */
public static void gzipFile(String from, String to) throws IOException {
// Create stream to read from the from file
FileInputStream in = new FileInputStream(from);
// Create stream to compress data and write it to the to file.
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
// Copy bytes from one stream to the other
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = in.read(buffer)) != -1)
Search WWH ::




Custom Search