目录
  1. 1. 打包
  2. 2. ZipArchiveOutputStream
JAVA操作commons-compress打zip包

文章首发于: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

文章作者: ClawHub
文章链接: https://www.clawhub.club/posts/2019/08/09/JAVA%E5%9F%BA%E7%A1%80/JAVA%E6%93%8D%E4%BD%9Ccommons-compress%E6%89%93zip%E5%8C%85/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ClawHub的博客
打赏
  • 微信
  • 支付宝
扫一扫关注ClawHub公众号,专注Java、技术分享、面试资源。

评论