Compress and unzip folders and files using java

If my application wants to use java to compress resultant files (filegroups) dynamically, what are the options available in Java?

Solution

public class FolderZiper {
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,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(),zip);
      }
    }
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>