【问题标题】:How to Unzip all the Zip folder in an directory in Java?如何解压缩Java目录中的所有Zip文件夹?
【发布时间】:2017-03-16 16:23:32
【问题描述】:

我想编写一个程序,它将获取文件夹中存在的所有 Zip 文件并解压缩到目标文件夹中。 我能够编写一个程序,我可以在其中解压缩一个 zip 文件,但我想解压缩该文件夹中存在的所有 zip 文件,我该怎么做?

【问题讨论】:

  • 你能发布你的代码吗?有一个很棒的功能,它可以在循环中很好地工作,但我们需要看看你在尝试什么。

标签: java windows zip unzip


【解决方案1】:

它不漂亮,但你明白了。

  1. 使用来自 Java 7 的 NIO Files api 流过滤掉 zip 文件的目录
  2. 使用 ZIP api 访问存档中的每个 ZipEntry
  3. 使用 NIO api 将文件写入指定目录

    public class Unzipper {
    
      public static void main(String [] args){
        Unzipper unzipper = new Unzipper();
        unzipper.unzipZipsInDirTo(Paths.get("D:/"), Paths.get("D:/unzipped"));
      }
    
      public void unzipZipsInDirTo(Path searchDir, Path unzipTo ){
    
        final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
        try (final Stream<Path> stream = Files.list(searchDir)) {
            stream.filter(matcher::matches)
                    .forEach(zipFile -> unzip(zipFile,unzipTo));
        }catch (IOException e){
            //handle your exception
        }
      }
    
     public void unzip(Path zipFile, Path outputPath){
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {
    
            ZipEntry entry = zis.getNextEntry();
    
            while (entry != null) {
    
                Path newFilePath = outputPath.resolve(entry.getName());
                if (entry.isDirectory()) {
                    Files.createDirectories(newFilePath);
                } else {
                    if(!Files.exists(newFilePath.getParent())) {
                        Files.createDirectories(newFilePath.getParent());
                    }
                    try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                        byte[] buffer = new byte[Math.toIntExact(entry.getSize())];
    
                        int location;
    
                        while ((location = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, location);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        }catch(IOException e){
            throw new RuntimeException(e);
            //handle your exception
        }
      }
    }
    

【讨论】:

    【解决方案2】:

    您可以使用 Java 7 Files API

    Files.list(Paths.get("/path/to/folder"))
        .filter(c -> c.endsWith(".zip"))
        .forEach(c -> unzip(c));
    

    【讨论】:

    • 从技术上讲,这会处理目录和所有子目录中的 zip 文件,而不仅仅是指定目录。 Files.list 会更准确地解决这个问题。
    • 感谢 Rainer 的回复,我应该在 .filter 中使用什么? .filter() 我已经为代码的第一行和最后一行提供了源文件夹和目标文件夹,但不确定如何过滤代码第二行中的 zip 文件。
    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多