java - 如何在 Java 中解压缩目录中的所有 Zip 文件夹?

标签 java windows zip unzip

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

最佳答案

它不漂亮,但你明白了。

  1. 使用NIO来自 Java 7 的文件 api 流过滤出 zip 文件的目录
  2. 使用ZIP用于访问存档中每个 ZipEntry 的 API
  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
        }
      }
    }
    

关于java - 如何在 Java 中解压缩目录中的所有 Zip 文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42839569/

相关文章:

java - 无法通过java和postman的多部分表单数据上传文件

.net - 如何检查是否安装了 .NET Framework

windows - Microsoft Windows Python-3.6 PyCrypto 安装报错

java - 使用java在 "zipping"目录时添加了不必要的文件结构?

java - 用Java解压缩内存中的ZIP文件

ruby - 从 Amazon S3 流式传输动态 zip

java - 如何获取在 void 方法中实例化的对象?

java - handshake_failure 找不到合适的证书

java - 在notify()之后线程不恢复执行

c - 安排 Windows 在 C 上启动