1. pom引入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.12</version>
</dependency>
2. 代码
/**
@param in 输入流
@param filePath: 带路径的会把文件夹一起打包,只有文件名的就在zip包根路径
@param res: http响应对象
*/
public void fileToZip(InputStream in,String filePath,HttpServletResponse res){
ZipArchiveOutputStream zip = new ZipArchiveOutputStream(res.getOutputStream());
ZipArchiveEntry entry = new ZipArchiveEntry(filePath);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
zip.putArchiveEntry(entry);
int c = 0;
while((c = in.read()) != -1){
zip.write(c);
}
in.close();
zip.closeArchiveEntry();
if (bos != null) {
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
3. 说明,ZipArchiveEntry 有多个构造,可以根据需求使用不同的构造方法:
public ZipArchiveEntry(String name){}
public ZipArchiveEntry(ZipEntry entry){}
public ZipArchiveEntry(File inputFile, String entryName){}
4. 参考:https://blog.csdn.net/u013055490/article/details/87604705(workbook打包zip)