Java Reference
In-Depth Information
Example 3−5: Compress.java (continued)
out.write(buffer, 0, bytes_read);
// And close the streams
in.close();
out.close();
}
/** Zip the contents of the directory, and save it in the zipfile */
public static void zipDirectory(String dir, String zipfile)
throws IOException, IllegalArgumentException {
// Check that the directory is a directory, and get its contents
File d = new File(dir);
if (!d.isDirectory())
throw new IllegalArgumentException("Compress: not a directory: " +
dir);
String[] entries = d.list();
byte[] buffer = new byte[4096]; // Create a buffer for copying
int bytes_read;
// Create a stream to compress data and write it to the zipfile
ZipOutputStream out =
new ZipOutputStream(new FileOutputStream(zipfile));
// Loop through all entries in the directory
for(int i = 0; i < entries.length; i++) {
File f = new File(d, entries[i]);
if (f.isDirectory()) continue; // Don't zip sub-directories
FileInputStream in = new FileInputStream(f); // Stream to read file
ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
out.putNextEntry(entry); // Store entry
while((bytes_read = in.read(buffer)) != -1) // Copy bytes
out.write(buffer, 0, bytes_read);
in.close();
// Close input stream
}
// When we're done with the whole loop, close the output stream
out.close();
}
/**
* This nested class is a test program that demonstrates the use of the
* static methods defined above.
**/
public static class Test {
/**
* Compress a specified file or directory. If no destination name is
* specified, append .gz to a file name or .zip to a directory name
**/
public static void main(String args[]) throws IOException {
if ((args.length != 1) && (args.length != 2)) { // check arguments
System.err.println("Usage: java Compress$Test <from> [<to>]");
System.exit(0);
}
String from = args[0], to;
File f = new File(from);
boolean directory = f.isDirectory(); // Is it a file or directory?
if (args.length == 2) to = args[1];
else { // If destination not specified
if (directory) to = from + ".zip";
// use a .zip suffix
else to = from + ".gz";
// or a .gz suffix
Search WWH ::




Custom Search