yangys
2024-10-30 25db770e621f1259b8d5b7fd514207f7481c2d0f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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<Path> {
    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);
    }
}