java.util.zip - 重新创建目录结构

43

我正试图使用 java.util.zip 压缩归档文件,遇到了很多问题,其中大部分都已得到解决。现在我终于得到了一些输出结果,但我仍然无法获得“正确”的输出。我有一个已提取的 ODT 文件(更适合称为目录),我对其进行了一些修改。现在我想将该目录压缩以重新创建 ODT 文件结构。将该目录压缩并将其重命名为以 .odt 结尾的文件名可以正常工作,因此不应该有问题。

主要问题是我丢失了目录的内部结构。一切变得“扁平化”,我似乎找不到保留原始多层结构的方法。如果能得到一些帮助,我会非常感激,因为我似乎找不到问题所在。

以下是相关的代码片段:

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
    FILEPATH.substring(0, FILEPATH.lastIndexOf(SEPARATOR) + 1).concat("test.zip")));
    compressDirectory(TEMPARCH, out);

SEPARATOR是系统文件分隔符,而FILEPATH是原始ODT文件的文件路径。为了测试目的,我只是将内容写入同一目录下名为test.zip的文件中,但没有覆盖原来的文件。

private void compressDirectory(String directory, ZipOutputStream out) throws IOException
{
    File fileToCompress = new File(directory);
    // list contents.
    String[] contents = fileToCompress.list();
    // iterate through directory and compress files.
    for(int i = 0; i < contents.length; i++)
    {
        File f = new File(directory, contents[i]);
        // testing type. directories and files have to be treated separately.
        if(f.isDirectory())
        {
            // add empty directory
            out.putNextEntry(new ZipEntry(f.getName() + SEPARATOR));
            // initiate recursive call
            compressDirectory(f.getPath(), out);
            // continue the iteration
            continue;
        }else{
             // prepare stream to read file.
             FileInputStream in = new FileInputStream(f);
             // create ZipEntry and add to outputting stream.
             out.putNextEntry(new ZipEntry(f.getName()));
             // write the data.
             int len;
             while((len = in.read(data)) > 0)
             {
                 out.write(data, 0, len);
             }
             out.flush();
             out.closeEntry();
             in.close();
         }
     }
 }

包含要压缩的文件的目录位于用户空间中,而不是与结果文件相同的目录中。我认为这可能会有问题,但我真的看不出来在哪里。此外,我想问题可能在于使用相同的流进行输出,但我也看不出来在哪里。我在一些示例和教程中看到他们使用了getPath()而不是getName(),但更改后给我一个空的zip文件。

8个回答

97

URI类对于处理相对路径非常有用。

File mydir = new File("C:\\mydir");
File myfile = new File("C:\\mydir\\path\\myfile.txt");
System.out.println(mydir.toURI().relativize(myfile.toURI()).getPath());

上述代码将输出字符串 path/myfile.txt

为了完整起见,这里提供一个压缩目录的zip方法:

  public static void zip(File directory, File zipfile) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
      ZipOutputStream zout = new ZipOutputStream(out);
      res = zout;
      while (!queue.isEmpty()) {
        directory = queue.pop();
        for (File kid : directory.listFiles()) {
          String name = base.relativize(kid.toURI()).getPath();
          if (kid.isDirectory()) {
            queue.push(kid);
            name = name.endsWith("/") ? name : name + "/";
            zout.putNextEntry(new ZipEntry(name));
          } else {
            zout.putNextEntry(new ZipEntry(name));
            copy(kid, zout);
            zout.closeEntry();
          }
        }
      }
    } finally {
      res.close();
    }
  }

这段代码无法保留日期,而且我不确定它对符号链接之类的内容会有何反应。它也没有尝试添加目录条目,因此空目录不会被包括在内。

相应的unzip命令:

  public static void unzip(File zipfile, File directory) throws IOException {
    ZipFile zfile = new ZipFile(zipfile);
    Enumeration<? extends ZipEntry> entries = zfile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      File file = new File(directory, entry.getName());
      if (entry.isDirectory()) {
        file.mkdirs();
      } else {
        file.getParentFile().mkdirs();
        InputStream in = zfile.getInputStream(entry);
        try {
          copy(in, file);
        } finally {
          in.close();
        }
      }
    }
  }

它们依赖的实用方法:

  private static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    while (true) {
      int readCount = in.read(buffer);
      if (readCount < 0) {
        break;
      }
      out.write(buffer, 0, readCount);
    }
  }

  private static void copy(File file, OutputStream out) throws IOException {
    InputStream in = new FileInputStream(file);
    try {
      copy(in, out);
    } finally {
      in.close();
    }
  }

  private static void copy(InputStream in, File file) throws IOException {
    OutputStream out = new FileOutputStream(file);
    try {
      copy(in, out);
    } finally {
      out.close();
    }
  }

缓冲区大小完全是任意的。


非常感谢!不过我无法看出您的压缩代码是如何保留原始目录格式的。在我使用的ODT中有空目录。据我所知,您的代码将永远不会创建这些目录。我是否可能遗漏了什么? - Eric Tobias
3
目录是以“/”结尾的空条目。我已修改了代码。 - McDowell
我调整了你的代码结构并放弃了递归调用。我认为这是错误的处理方式。代码运行顺畅,只有一个例外:即使子目录不为空,它也会向大多数子目录添加空文件夹。我发现删除以下行可以解决问题:name = name.endsWith("/") ? name : name + "/"; 我怀疑通过追加“\”来添加目录时,也会在其中创建一个空文件夹。通过让ZipEntries处理结构构建,一切似乎都很好。感谢大家的帮助! - Eric Tobias
潜在的 NPE:如果目录为空,directory.listFiles() 将返回 null! - Axel Fontaine
如果目录为空,它将返回一个空目录 - doc - 但在某些情况下可能会返回null,因此最好在这种情况下抛出IOException。 - McDowell
非常感谢你节省了我的时间! - ojblass

7

我看到你的代码中有两个问题:

  1. 你没有保存目录路径,因此无法找回它。
  2. 在Windows上,你需要使用“/”作为路径分隔符。一些解压程序不支持“\”。

我提供了自己的版本供你参考。我们使用这个版本来压缩照片以便下载,所以它可以与各种解压程序配合使用。它保留了目录结构和时间戳。

  public static void createZipFile(File srcDir, OutputStream out,
   boolean verbose) throws IOException {

  List<String> fileList = listDirectory(srcDir);
  ZipOutputStream zout = new ZipOutputStream(out);

  zout.setLevel(9);
  zout.setComment("Zipper v1.2");

  for (String fileName : fileList) {
   File file = new File(srcDir.getParent(), fileName);
   if (verbose)
    System.out.println("  adding: " + fileName);

   // Zip always use / as separator
   String zipName = fileName;
   if (File.separatorChar != '/')
    zipName = fileName.replace(File.separatorChar, '/');
   ZipEntry ze;
   if (file.isFile()) {
    ze = new ZipEntry(zipName);
    ze.setTime(file.lastModified());
    zout.putNextEntry(ze);
    FileInputStream fin = new FileInputStream(file);
    byte[] buffer = new byte[4096];
    for (int n; (n = fin.read(buffer)) > 0;)
     zout.write(buffer, 0, n);
    fin.close();
   } else {
    ze = new ZipEntry(zipName + '/');
    ze.setTime(file.lastModified());
    zout.putNextEntry(ze);
   }
  }
  zout.close();
 }

 public static List<String> listDirectory(File directory)
   throws IOException {

  Stack<String> stack = new Stack<String>();
  List<String> list = new ArrayList<String>();

  // If it's a file, just return itself
  if (directory.isFile()) {
   if (directory.canRead())
    list.add(directory.getName());
   return list;
  }

  // Traverse the directory in width-first manner, no-recursively
  String root = directory.getParent();
  stack.push(directory.getName());
  while (!stack.empty()) {
   String current = (String) stack.pop();
   File curDir = new File(root, current);
   String[] fileList = curDir.list();
   if (fileList != null) {
    for (String entry : fileList) {
     File f = new File(curDir, entry);
     if (f.isFile()) {
      if (f.canRead()) {
       list.add(current + File.separator + entry);
      } else {
       System.err.println("File " + f.getPath()
         + " is unreadable");
       throw new IOException("Can't read file: "
         + f.getPath());
      }
     } else if (f.isDirectory()) {
      list.add(current + File.separator + entry);
      stack.push(current + File.separator + f.getName());
     } else {
      throw new IOException("Unknown entry: " + f.getPath());
     }
    }
   }
  }
  return list;
 }
}

感谢您的贡献。我非常感激您提供的代码示例,但是我不确定它如何帮助我找到我的代码中的错误,原因在于:调用该函数的初始值为完整的目录路径,这将传递到函数中;其次,我的SEPARATOR常量是通过System.getProperty("file.separator")初始化的,这将给我操作系统默认的文件分隔符。我永远不会硬编码分隔符,因为那会假定您的代码只能部署在一个特定的操作系统上。 - Eric Tobias
4
在ZIP中不要使用File.separator,根据规范,分隔符必须是"/"。如果你在Windows上,你必须将文件打开为"D:\dir\subdir\file",但是ZIP条目必须为"dir/subdir/file"。 - ZZ Coder
1
我知道了。谢谢你指出这一点。没想到ZIP文件是如此挑剔! :) - Eric Tobias

4

3

这是另一个例子(递归),它还允许您在zip中包含/排除包含文件夹:

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

public class ZipUtil {

  private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

  public static void main(String[] args) throws Exception {
    zipFile("C:/tmp/demo", "C:/tmp/demo.zip", true);
  }

  public static void zipFile(String fileToZip, String zipFile, boolean excludeContainingFolder)
    throws IOException {        
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));    

    File srcFile = new File(fileToZip);
    if(excludeContainingFolder && srcFile.isDirectory()) {
      for(String fileName : srcFile.list()) {
        addToZip("", fileToZip + "/" + fileName, zipOut);
      }
    } else {
      addToZip("", fileToZip, zipOut);
    }

    zipOut.flush();
    zipOut.close();

    System.out.println("Successfully created " + zipFile);
  }

  private static void addToZip(String path, String srcFile, ZipOutputStream zipOut)
    throws IOException {        
    File file = new File(srcFile);
    String filePath = "".equals(path) ? file.getName() : path + "/" + file.getName();
    if (file.isDirectory()) {
      for (String fileName : file.list()) {             
        addToZip(filePath, srcFile + "/" + fileName, zipOut);
      }
    } else {
      zipOut.putNextEntry(new ZipEntry(filePath));
      FileInputStream in = new FileInputStream(srcFile);

      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int len;
      while ((len = in.read(buffer)) != -1) {
        zipOut.write(buffer, 0, len);
      }

      in.close();
    }
  }
}

2
如果您不想麻烦处理字节输入流、缓冲区大小和其他低级细节,可以从您的Java代码中使用Ant的Zip库(Maven依赖项可以在这里找到)。以下是我如何制作包含文件和目录列表的zip文件的方法:
public static void createZip(File zipFile, List<String> fileList) {

    Project project = new Project();
    project.init();

    Zip zip = new Zip();
    zip.setDestFile(zipFile);
    zip.setProject(project);

    for(String relativePath : fileList) {

        //noramalize the path (using commons-io, might want to null-check)
        String normalizedPath = FilenameUtils.normalize(relativePath);

        //create the file that will be used
        File fileToZip = new File(normalizedPath);
        if(fileToZip.isDirectory()) {
            ZipFileSet fileSet = new ZipFileSet();
            fileSet.setDir(fileToZip);
            fileSet.setPrefix(fileToZip.getPath());
            zip.addFileset(fileSet);
        } else {
            FileSet fileSet = new FileSet();
            fileSet.setDir(new File("."));
            fileSet.setIncludes(normalizedPath);
            zip.addFileset(fileSet);
        }
    }

    Target target = new Target();
    target.setName("ziptarget");
    target.addTask(zip);
    project.addTarget(target);
    project.executeTarget("ziptarget");
}

1

在Windows中压缩文件夹及其子文件夹的内容时,

请替换,

out.putNextEntry(new ZipEntry(files[i])); 

使用

out.putNextEntry(new ZipEntry(files[i]).replace(inFolder+"\\,"")); 

1
我想在这里提出一个建议/提醒:
如果您将输出目录定义为与输入目录相同,则需要将每个文件的名称与输出.zip文件的名称进行比较,以避免将文件压缩到自身内部,从而生成一些不必要的行为。希望这能有所帮助。

0

这段代码对我有效。不需要第三方库。

public static void zipDir(final Path dirToZip, final Path out) {
    final Stack<String> stackOfDirs = new Stack<>();
    final Function<Stack<String>, String> createPath = stack -> stack.stream().collect(Collectors.joining("/")) + "/";
    try(final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
        Files.walkFileTree(dirToZip, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
                stackOfDirs.push(dir.toFile().getName());
                final String path = createPath.apply(stackOfDirs);
                final ZipEntry zipEntry = new ZipEntry(path);
                zipOut.putNextEntry(zipEntry);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                final String path = String.format("%s%s", createPath.apply(stackOfDirs), file.toFile().getName());
                final ZipEntry zipEntry = new ZipEntry(path);
                zipOut.putNextEntry(zipEntry);
                Files.copy(file, zipOut);
                zipOut.closeEntry();
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
                final StringWriter stringWriter = new StringWriter();
                try(final PrintWriter printWriter = new PrintWriter(stringWriter)) {
                    exc.printStackTrace(printWriter);
                    System.err.printf("Failed visiting %s because of:\n %s\n",
                            file.toFile().getAbsolutePath(), printWriter.toString());
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
                stackOfDirs.pop();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接