Java 压缩成zip文件
综述
在《 把多个文件打包压缩成tar.gz文件并解压的Java实现》中介绍了如何把文件压缩车gz文件,这里介绍如何把文件压缩成zip文件。支持如下方式的压缩:
- 压缩单个文件
- 压缩文件夹下的所有文件
源码
话不多说,直接上源代码:
/**
* 压缩指定文件夹中的所有文件,生成指定名称的zip压缩包
*
* @param sourcePath 需要压缩的文件名称列表(包含相对路径)
* @param zipOutPath 压缩后的文件名称
**/
public static void batchZipFiles(String sourcePath, String zipOutPath) {
ZipOutputStream zipOutputStream = null;
WritableByteChannel writableByteChannel = null;
MappedByteBuffer mappedByteBuffer = null;
try {
zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutPath));
writableByteChannel = Channels.newChannel(zipOutputStream);
File file = new File(sourcePath);
for (File source : file.listFiles()) {
long fileSize = source.length();
//利用putNextEntry来把文件写入
zipOutputStream.putNextEntry(new ZipEntry(source.getName()));
long read = Integer.MAX_VALUE;
int count = (int) Math.ceil((double) fileSize / read);
long pre = 0;
//由于一次映射的文件大小不能超过2GB,所以分次映射
for (int i = 0; i < count; i++) {
if (fileSize - pre < Integer.MAX_VALUE) {
read = fileSize - pre;
}
mappedByteBuffer = new RandomAccessFile(source, "r").getChannel()
.map(FileChannel.MapMode.READ_ONLY, pre, read);
writableByteChannel.write(mappedByteBuffer);
pre += read;
}
}
mappedByteBuffer.clear();
} catch (Exception e) {
log.error("Zip more file error, fileNames: " + sourcePath, e);
} finally {
try {
if (null != zipOutputStream) {
zipOutputStream.close();
}
if (null != writableByteChannel) {
writableByteChannel.close();
}
if (null != mappedByteBuffer) {
mappedByteBuffer.clear();
}
} catch (Exception e) {
log.error("Zip more file error, file names are:" + sourcePath, e);
}
}
}
小结
如果您在工作过程中遇到有关zip的压缩问题,不妨在下方留言,大家一起来应对助您解决问题。如果感觉本文对您有帮助,请点赞并收藏。
Reference
读后有收获,小礼物走一走,请作者喝咖啡。

作者:楼兰胡杨
本文版权归作者和博客园共有,欢迎转载,但请注明原文链接,并保留此段声明,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南