Compress files using with ZIP

 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {
  public static void gzipFile(String from, String to) throws IOException {
    FileInputStream in = new FileInputStream(from);
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1)
      out.write(buffer, 0, bytesRead);
    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("Not a directory:  "
          + dir);
    String[] entries = d.list();
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    for (int i = 0; i < entries.length; i++) {
      File f = new File(d, entries[i]);
      if (f.isDirectory())
        continue;//Ignore directory
      FileInputStream in = new FileInputStream(f); // Stream to read file
      ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
      out.putNextEntry(entry); // Store entry
      while ((bytesRead = in.read(buffer)) != -1)
        out.write(buffer, 0, bytesRead);
      in.close(); 
    }
    out.close();
  }

  public static void main(String args[]) throws IOException {
    String from = ".";
    File f = new File(from);
    boolean directory = f.isDirectory(); // Is it a file or directory?

    Compress.zipDirectory(from, from + ".zip");
    Compress.gzipFile(from, from + ".gz");
  }
}
  
Home 
  Java Book 
    Runnable examples  

IO File:
  1. Compare File Dates
  2. Compress files using with ZIP
  3. Concatenate files
  4. Copy a File with NIO FileChannel and ByteBuffer
  5. Copy a file with FileReader and FileWriter
  6. Copy a file with InputStream and OutputStream
  7. Copy a file and overwrite
  8. Delete a file
  9. Delete File Recursively
  10. Get readable file size
  11. Move a file
  12. Rename a file
  13. Report a file's status
  14. Search a file by regular expressions
  15. Touch a file: set File Last Modified Time