java - 使用 Java 压缩和解压缩文件夹和文件

标签 java zip gzip unzip

如果我的应用程序想要以动态方式使用 java 压缩结果文件(文件组),Java 中有哪些可用选项? 当我浏览时,我有 java.util.zip 包可以使用,但是有没有其他方法可以使用它来实现?

最佳答案

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);
      }
    }
  }
}

关于java - 使用 Java 压缩和解压缩文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271801/

相关文章:

java - JBoss 部署错误 - 服务失败

java - 将已压缩的文件插入 zip 文件中

javascript - 提供 JavaScript 文件时,默认 gzip 是否安全

java - 内部类的目的是什么

java - 如何比较两个 Joda 时间段

php - 使用 PHP 压缩的文件在提取后生成 cpgz 文件

闭源应用程序的 C++ 压缩 (zip) 库

Ruby 流式传输 tar/gz

python 未使用 gzip 读取 gzip 文件

java - 在 Tomcat 7 64 位 jre6 上禁用 SSLv3