package com.qianwen.smartman.common.utils; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFileTree extends SimpleFileVisitor { private ZipOutputStream zipOutputStream; private Path sourcePath; public void zipFile(String sourceDir) throws IOException { try { String zipFileName = sourceDir + ".zip"; this.zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName)); this.sourcePath = Paths.get(sourceDir, new String[0]); Files.walkFileTree(this.sourcePath, this); if (null != this.zipOutputStream) { this.zipOutputStream.close(); } } catch (Throwable th) { if (null != this.zipOutputStream) { this.zipOutputStream.close(); } throw th; } } @Override // java.nio.file.SimpleFileVisitor, java.nio.file.FileVisitor public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { Path targetFile = this.sourcePath.relativize(file); this.zipOutputStream.putNextEntry(new ZipEntry(targetFile.toString())); byte[] bytes = Files.readAllBytes(file); this.zipOutputStream.write(bytes, 0, bytes.length); this.zipOutputStream.closeEntry(); return FileVisitResult.CONTINUE; } @Override // java.nio.file.SimpleFileVisitor, java.nio.file.FileVisitor public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return super.preVisitDirectory(dir, attrs); } @Override // java.nio.file.SimpleFileVisitor, java.nio.file.FileVisitor public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return super.postVisitDirectory(dir, exc); } @Override // java.nio.file.SimpleFileVisitor, java.nio.file.FileVisitor public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return super.visitFileFailed(file, exc); } }