java中Zip的压缩和解压

本文介绍使用Java实现ZIP文件的压缩与解压方法。通过ZipEntry、ZipOutputStream及ZipInputStream三个核心类来操作文件。文章详细展示了如何将指定文件压缩成ZIP格式,并将ZIP文件还原为原始文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java提供的ZIP压缩方法

用到了三个类 ZipEntry ZipOutputStream ZipInputStream

代码如下

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Zipyasuojiaya {
	public static void main(String args[]) {
		file2zip("C:\\abcdefg.zip");
		zip2file();
	}

	// 文件转zip文件,这里模拟一个文件夹和文件压缩
	public static void file2zip(String zipPath) {
		try {
			File zipFile = new File(zipPath);
			zipFile.getParentFile().mkdirs();
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
					zipPath));

			// 写一个文件
			File f = new File("C:\\1.txt");
			// 添加一个ZipEntry对象
			out.putNextEntry(new ZipEntry("copy1.txt"));
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
			// 在压缩文件中创建一个文件夹
			out.putNextEntry(new ZipEntry("abc/"));
			// 向这个压缩中的文件夹写入一个文件
			File f1 = new File("C:\\1.txt");
			// 注意这里是文件在压缩文件中的位置,在解压的时候它的那么也是这个
			out.putNextEntry(new ZipEntry("abc/copy2.txt"));
			FileInputStream in1 = new FileInputStream(f1);
			int b1;
			while ((b1 = in1.read()) != -1) {
				out.write(b1);
			}
			in1.close();
			System.out.println("压缩完成");
			// 没有关闭的话文件会存在异常
			out.close();
		} catch (Exception e) {
		}
	}

	// 压缩文件转回文件形式
	public static void zip2file() {
		try {
			ZipInputStream in = new ZipInputStream(new FileInputStream(
					"C:\\abcdefg.zip"));
			ZipEntry z = null;
			while ((z = in.getNextEntry()) != null) {
				if (z.isDirectory()) {
					File f = new File("C:\\123\\" + z.getName() + "\\");
					// 这里将文件夹创建,压缩文件夹中的文件也会当做一个个ZipEntry类,文件夹也是一个ZipEntry类。
					f.mkdirs();
				} else {
					File f = new File("C:\\123\\" + z.getName());
					OutputStream out = new FileOutputStream(f);
					int b;
					while ((b = in.read()) != -1) {
						out.write(b);
					}
					out.close();
				}
			}
			// 记得关闭
			in.close();

		} catch (Exception e) {
			// 这里最好写点东西,要不出错也不知道
			e.printStackTrace();
		}
	}
}
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值