Jul 6, 2010

Zip Files or Folders using Java



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

/**
* @param source file or folder to compress for
* @param destination zip file located at
* @param comment the comment of zip file, if comment == null will ignore
* @param level compression level, reference to Deflater class
*/
public static void compress(File source, File destination, String comment, int level) throws IOException{
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination));
    zos.setComment(comment);
    zos.setLevel(level);
    compress(zos, source.getParent(), source);
    zos.flush();
    zos.close();
}

// this method will be hidden
private static void compress(ZipOutputStream zos, String rootpath, File source) throws IOException{
    String filename = source.toString().substring(rootpath.length() + 1);
    if (source.isFile()){
        zos.putNextEntry(new ZipEntry(filename));
        FileInputStream fis = new FileInputStream(source);
        byte[] buffer = new byte[1024];
        for (int length; (length = fis.read(buffer)) > 0;){
            zos.write(buffer, 0, length);
        }
        fis.close();
        zos.closeEntry();
    } else if (source.isDirectory()){
        zos.putNextEntry(new ZipEntry(filename + "/"));
        zos.closeEntry();
        File[] files = source.listFiles();
        for (File file : files){
            compress(zos, rootpath, file);
        }
    }
}

You could modify above Java code if you would like to enhance for compressing many files or folders.
Seems like this

public static void compress(File[] files, File destination, String comment, int level) throws IOException{
    // ...
}


2 comments:

club penguins cheats said...

Thank you for sharing this great piece. Very inspiring! (as always, btw)

Jani Trapani said...

Amazing write-up. Did you read the related piece in the Huffington Post some time again? Evidently increasingly more mainstream media are having to pay attention to this. I hope your web site will get increasingly more subscribers as this issue gets much more coverage, as it is a great useful resource.

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code