Java --zip文件的解压

没什么好说的,直接上代码分析

package com.app.zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author 黄经理
 *	解压zip文件代码
 *	说明:我在此处解压的是Tomcat的zip格式的压缩包
 *	为了操作成功,在文件的路径中尽量不要出现中文
 */
public class UnZip {
	public static void main(String[] args) {
		String source="E:\\tomcat.zip";
		File sourceFile=new File(source);
		String targetFile="E:\\zip";
		unzip(sourceFile,targetFile);
	}

	/**
	 * @param sourceFile 源文件
	 * @param targetFile 目标文件
	 */
	public static void unzip(File sourceFile, String targetFile) {
		//判断源文件是否存在
		if(!sourceFile.exists()) {
			//源文件不存在  抛出一个异常
			throw new RuntimeException(sourceFile.getPath()+"路径下的文件不存在");
		}
		/* 源文件存在 开始解压
		 * ZipEntry:也就是代表zip压缩文件条目对象		
		 */
		ZipFile zipFile=null;
		try {
			//将File对象转化为ZipFile对象
			zipFile = new ZipFile(sourceFile);
			Enumeration<? extends ZipEntry> entries = zipFile.entries();
			while(entries.hasMoreElements()) {
				ZipEntry zipEntry = entries.nextElement();
				System.out.println("解压:"+zipEntry.getName());
				//如果是文件夹 就创建一个文件夹
				if(zipEntry.isDirectory()) {
					//zipEntry是文件夹
					String dirPath=targetFile+"/"+zipEntry.getName();
					File dir = new File(dirPath);
					dir.mkdirs();
				}else {
					//zipEntry是文件
					File target = new File(targetFile+"/"+zipEntry.getName());
					//验证该文件的父文件夹是否存在
					if(!target.getParentFile().exists()) {
						target.getParentFile().mkdirs();
					}
					target.createNewFile();
					//将压缩文件的内容通过流写入到该文件夹中
					InputStream is = zipFile.getInputStream(zipEntry);
					FileOutputStream fOS = new FileOutputStream(target);
					int len;
					byte[] buf=new byte[1024];
					while((len=is.read(buf))!=-1) {
						fOS.write(buf, 0, len);
					}
					//释放资源 先开后关  后开先关
					fOS.close();
					is.close();
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("解压出现异常");
		}finally {
			if(zipFile!=null) {
				try {
					zipFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值