java如何使用java.util.zip进行压缩和解压呢?

戚薇 Java经验 发布时间:2023-06-24 22:48:31 阅读数:18369 1
下文笔者讲述使用java.util.zip进行压缩和解压的方法及示例分享,如下所示
压缩和解压的实现思路:
    1.引入
	   java.util.zip.ZipEntry;
       java.util.zip.ZipInputStream;
       java.util.zip.ZipOutputStream;
    2.定义 ZipOutputStream对象
	   使用ZipOutputStream对象的putNextEntry
	       方法向压缩文件中添加信息
	   即可实现添加操作
	    如下所示
	   解压同理
例:解压和压缩的示例
package com.java265;
 
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;
  
public class TestZip {
  
	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();
		}
		
	}
}
版权声明

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

本文链接: https://www.Java265.com/JavaJingYan/202306/16876181516886.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

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

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者