关键词:ZipOutputStream ZipInoutStream
最近在工作中有需求需要在浏览器中一次性下载多个文件,于是想到了使用压缩的功能。百度了一下,发现很多博客的内容都大致相同,不太方便使用。于是自己写了这么一个工具类,使用JDK中自带的ZipOutputStream和ZipInoutStream实现对文件的压缩和解压。
█ 源码
/**
* 使用方法:
* byte[] bytes = ZipUtil.createZipObject().addFile(fileBytes, "hello.xls").create();
*
* 需要添加多个文件就调用多次addFile,最后调用create生成字节数组即可
*
*/
public class ZipUtil {
private ZipUtil() {
throw new RuntimeException("Illegal operation");
}
// 压缩文件
public static ZipObject createZipObject() {
return new ZipObject();
}
// 解压文件,参数是压缩文件字节数组
public static UnZipObject createUnZipObject(byte[] bytes) {
if (bytes==null || bytes.length==0) {
throw new IllegalArgumentException("bytes is null");
}
return new UnZipObject(bytes);
}
public static class ZipObject {
// 工具流
private ZipOutputStream zos;
// 使用带有缓冲功能的文件流存储文件
private ByteArrayOutputStream bos;
private ZipObject() {
bos = new ByteArrayOutputStream();
// 文件数据流