JavaDemo——使用java.util.zip压缩和解压

Demo:

/**
 * 2019年6月20日下午4:59:37
 */
package testzip;

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

/**
 * @author XWF
 *
 */
public class TestZip {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		doZip();
		doUnzip();
	}

	public static void doZip() {
		try {
			//定义生成压缩的文件
			File zipf = new File("hello.zip");
			if(!zipf.exists()) {
				System.out.println("创建新zip文件结果:" + zipf.createNewFile());
			}
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipf));
			//需要压缩的文件
			File infile = new File("testzip.txt");
			FileInputStream fis = new FileInputStream(infile);
			//设置zip文件里组织结构
			zos.putNextEntry(new ZipEntry(infile.getName()));//压缩文件里直接用同名文件压缩
			int len = 0;
			byte[] b = new byte[1024];
			while((len = fis.read(b)) > 0) {
				zos.write(b, 0, len);
			}
			fis.close();
			//在压缩文件里再保存一份testzip.txt的压缩,并换目录和名字
			zos.putNextEntry(new ZipEntry("newFolder/a.txt"));//压缩文件里有一个叫newFolder的文件夹,里面保存testzip.txt的压缩,并用a.txt命名
			fis = new FileInputStream(infile);
			while((len = fis.read(b)) > 0) {
				zos.write(b, 0, len);
			}
			
			zos.closeEntry();
			zos.close();
			fis.close();
			System.out.println("压缩完成。");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void doUnzip() {
		try {
			File zipFile = new File("hello.zip");
			ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
			ZipEntry zipEntry = null;
			while((zipEntry = zis.getNextEntry()) != null) {
				System.out.println("zipEntry.getName:" + zipEntry.getName());
				int index = zipEntry.getName().lastIndexOf("/");
				String newFileName = zipEntry.getName().substring(index == -1?0:index+1);//去掉压缩包里的文件夹,这里只要文件名
				File newFile = new File("unzip_"+newFileName);
				FileOutputStream fos = new FileOutputStream(newFile);
				int len = 0;
				byte[] b = new byte[1024];
				while((len = zis.read(b)) > 0) {
					fos.write(b, 0, len);
					fos.flush();
				}
				fos.close();
			}
			zis.closeEntry();
			zis.close();
			System.out.println("解压完成。");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值