Java如何将“指定路径或文件”压缩为zip文件呢?

乔欣 Java经验 发布时间:2023-02-21 16:48:40 阅读数:955 1
下文笔者讲述使用java代码生成一个压缩文件的方法分享,如下所示

Java代码生成压缩文件的实现思路

借助ZipOutputStream对象即可将指定路径压缩为一个压缩文件
例:java生成压缩文件的工具类
 /**
 *  压缩指定文件夹中的所有文件,生成指定名称的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);
		}
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16769697435865.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者