ZipUtil.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package com.nokia.finance.tasks.utils;
  2. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  3. import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
  4. import java.io.IOException;
  5. import java.nio.file.FileVisitResult;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.SimpleFileVisitor;
  9. import java.nio.file.attribute.BasicFileAttributes;
  10. public class ZipUtil {
  11. /**
  12. * zip压缩文件夹不包括文件夹本身
  13. * @param inputDir 文件夹
  14. * @param outputFile 压缩文件
  15. */
  16. public static void zipDirNonSelf(Path inputDir, Path outputFile) throws IOException {
  17. try (ZipArchiveOutputStream os = new ZipArchiveOutputStream(Files.newOutputStream(outputFile))) {
  18. os.setLevel(9);
  19. Files.walkFileTree(inputDir, new SimpleFileVisitor<>() {
  20. @Override
  21. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  22. String relativePath = inputDir.relativize(file).toString();
  23. ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), relativePath);
  24. os.putArchiveEntry(entry);
  25. Files.copy(file, os);
  26. os.closeArchiveEntry();
  27. return FileVisitResult.CONTINUE;
  28. }
  29. });
  30. }
  31. }
  32. }