tags:

views:

575

answers:

4

If My Application wants to zip the Resultant files(group of Files) using java in a dynamic way, what are the available options in Java? When i Browsed I have got java.util.zip package to use, but is there any other way where I can use it to implement?

A: 

You can use ZIP file handling library that comes with JDK Also this tutorials might be helpful.

Upul
A: 

Compressign and decompressing using java should tell your everything your need to know. java.util.zip implements the deflate (zip) algorithm what else do you need ?

amo-ej1
+2  A: 
public class FolderZiper {
  public static void main(String[] a) throws Exception {
    zipFolder("c:\\a", "c:\\a.zip");
  }

  static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;

    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);

    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();
  }

  static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
      throws Exception {

    File folder = new File(srcFile);
    if (folder.isDirectory()) {
      addFolderToZip(path, srcFile, zip);
    } else {
      byte[] buf = new byte[1024];
      int len;
      FileInputStream in = new FileInputStream(srcFile);
      zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
      while ((len = in.read(buf)) > 0) {
        zip.write(buf, 0, len);
      }
    }
  }

  static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
      throws Exception {
    File folder = new File(srcFolder);

    for (String fileName : folder.list()) {
      if (path.equals("")) {
        addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
      } else {
        addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
      }
    }
  }
}
Yashwant Chavan
+2  A: 

The original Java implementation is known to have some bugs related to files encoding. For example it can't properly handle filenames with umlauts.

TrueZIP is an alternative that we've used in our project: https://truezip.dev.java.net/ Check the documentation on the site.

Daniel Bleisteiner