文章首发于:clawhub.club


引入maven依赖:

1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>

打包

将path文件夹下所有文件都打包到out文件中。

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
/**
* Do zip pack.
*
* @param path the path
* @param out the out
* @throws IOException the io exception
*/
public static void doZipPack(Path path, Path out) throws IOException {
//zip流
ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(out.toFile());
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ZipArchiveEntry zae = new ZipArchiveEntry(file.toFile(), "/" + file.getFileName().toString());
zaos.putArchiveEntry(zae);
InputStream is = new FileInputStream(file.toFile());
byte[] b = new byte[PicConstant.ONE_ZORE_TWO_FOUR * PicConstant.FIVE];
int i;
while ((i = is.read(b)) != -1) {
zaos.write(b, 0, i);
}
is.close();
zaos.closeArchiveEntry();
return FileVisitResult.CONTINUE;
}

});
//关流
zaos.finish();
zaos.close();
}

ZipArchiveOutputStream

OutputStream.png