在zip文件中维护Windows目录

时间:2011-10-27 20:44:47

标签: java windows zip directory

我已经查看了最近的问题,但我无法找到问题的解决方案。我需要压缩一个包含一堆目录的目录,这些目录都包含内容(基本上是文本文件)。当我打开zip时,我希望得到相同的目录列表。

我的问题是我可以压缩内容,但我的zip文件只出现了普通文件(没有目录)或者它出现了损坏。有没有人这样做过?

我发布的代码一直在生成腐败或看似空的拉链。以下是我的方法(总结)

public zipDir

File dirObj = new File(fileDirectory);
    String outFilename = zipDirectory+File.separatorChar+filename+".zip";
    log.info("Zip Directory: " + outFilename);
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
    System.out.println("Creating : " + outFilename);
    addDir(dirObj, out);
    out.close();

addDir

File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
      if (files[i].isDirectory()) {
        addDir(files[i], out);
        continue;
      }
      FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
      System.out.println(" Adding: " + files[i].getAbsolutePath());
      out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
      int len;
      while ((len = in.read(tmpBuf)) > 0) {
        out.write(tmpBuf, 0, len);
      }
      out.closeEntry();
      in.close();
    }

主要

zipDir(filename, properties);

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。这段代码完全符合我的需要。它会压缩目录并维护目录结构。

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

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