繁体   English   中英

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

[英]How to Unzip all the Zip folder in an directory in Java?

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

它不漂亮,但你明白了。

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

您可以使用 Java 7 Files API

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM