Java 压缩成zip文件
2021/12/25 20:37:14
本文主要是介绍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
- https://www.www.zyiz.net/content-1-924178.html
这篇关于Java 压缩成zip文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?