栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

zip压缩文件的读取和写入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

zip压缩文件的读取和写入

文章目录
  • 前言
    • 一、ZipInputStream
    • 二、ZipOutputStream


前言

在Java中,zip压缩文件是怎样读取和写入的?这里我们需要引入ZipInputStream 和 ZipOutputStream。

一、ZipInputStream

ZipInputStream是一种读取zip压缩文件的输入流,它的基本用法:创建一个ZipInputStream对象,因为它继承自FiterInputStream,因此它创建对象必须传入一个输入流(例如:FileInputStream)作为数据源,然后调用getNextEntry()方法,直到返回null,表示zip流结束。
一个ZipEntry对象可能表示一个压缩文件或目录,如果是压缩文件,调用read()方法不断读取,直到返回-1;
代码示例如下:

public static void main(String[] args) {
		// 要进行解压的zip文件
		File zipFile = new File("D:\Desktop.zip");

		// 1.创建解压缩目录
		// 获取zip文件的名称
		String zipFileName = zipFile.getName();

		// 根据zip文件名称,提取压缩目录的名称
		String targetFileName = zipFileName.substring(0, zipFileName.indexOf("."));

		// 创建解压缩目录
		File targetDir = new File(zipFile.getParent() + "\" + targetFileName);

		while (!targetDir.exists()) {
			targetDir.mkdir();// 创建目录
		}
		// 2.解析读取zip文件
		try (ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile), Charset.forName("gbk"))) {
			// 遍历zip压缩包中的每个子文件
			ZipEntry zipEntry = null;
			while ((zipEntry = in.getNextEntry()) != null) {
				// 获取zip压缩包中的子文件名称
				String zipEntryFileName = zipEntry.getName();
				// 创建该文件的输出流
				String zipFilePath = targetDir.getPath() + "\" + zipEntryFileName;

				//输出流定义在try()块,结束自动清空缓冲区并关闭
				try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(zipFilePath));) {
					// 读取该子文件的字节内容
					byte[] buff = new byte[1024];
					int len = -1;
					while ((len = in.read(buff)) != -1) {
						out.write(buff, 0, len);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
二、ZipOutputStream

ZipOutputStream是一种将内容写入zip压缩文件的输出流,它继承自FiterOutputStream,它的基本用法:创建一个ZipOutputStream对象,它创建对象必须传入一个输出流(例如:FileOutputStream),每写入一个文件前,先调用putNextEntry(),然后调用write()方法写入byte[ ]数据,最后调用closeEntry()结束文件的打包。
代码示例如下:

public static void main(String[] args) {
		//原始目录
		File rootDir = new File("D:\Desktop");
		//将原始目录中的文件,“写入”zip压缩文件
		try (ZipOutputStream out = new ZipOutputStream(
				 new FileOutputStream(rootDir.getParent()+"//"+rootDir.getName()+"1.zip"))) {
			//获取并遍历原始目录下的子文件列表
			File[] files = rootDir.listFiles();
			for(File f : files) {
				//创建一个ZipEntry
				out.putNextEntry(new ZipEntry(f.getName()));
				
				//将原文件的字节内容,写入Zip压缩包
				out.write(Files.readAllBytes(f.toPath()));
				
				//结束当前ZipEntry
				out.closeEntry();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939508.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号