Apache Ant包进行ZIP文件压缩

Apache Ant包进行ZIP文件压缩

许多年前就遇到过这种业务,对ZIP标准压缩文件解压。之前写的操作类现在找不到了,最近项目中又要处理这种业务,所以重新写了一个。Java提供了处理ZIP包的API。但是对中文支持不是很好,所以我直接用Apache Ant里的ZIP操作API来进行处理。ANT的API解决了中文支持问题,而且用起来也非常方便。以下是操作类。

以下的类只是用到Apache的一小部分功能。具体更多的API,请参考文档。在此不多说明了。

* 在项目中导入Apache的ant.jar包到Lib中。

/*
  * All rights reserved.
 * @author: JODY
 * @Date: 2008-05-27
 * @Time: 0:15:04
 */
package cn.com.jody.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.tools.zip.ZipEntry;

/*
 * <p>
 * 功能描述 标准ZIP文件解压缩<br>
 * 支持中文目录、文件名<br>
 * 无限级目录结构
 * </p>
 * 文件名称:ExtractZIP.java<br>
 * 类型名称:ExtractZIP<br>
 * @author: JODY
 */
public class ExtractZIP {
	
	public ExtractZIP(){
		
	}
	/**
	 * 解压静态方法
	 * @param zipFileName
	 * @param outputDirectory
	 * @throws Exception
	 */
	public static void extract(String zipFileName,String outputDirectory) throws Exception{
		try {
			org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);
			java.util.Enumeration e = zipFile.getEntries();

			org.apache.tools.zip.ZipEntry zipEntry = null;

			while (e.hasMoreElements()){
				zipEntry = (ZipEntry)e.nextElement();
				//System.out.println("unziping "+zipEntry.getName());
				if (zipEntry.isDirectory()){
					String name=zipEntry.getName();
					name=name.substring(0,name.length()-1);		
					mkDirs(outputDirectory+File.separator+name);					
					//System.out.println("创建目录:"+outputDirectory+File.separator+name);

				}else{
					String name=zipEntry.getName();
					String dir = name.substring(0,name.lastIndexOf("/"));
					mkDirs(outputDirectory+File.separator+dir);					
					//System.out.println("创建文件:"+outputDirectory+File.separator+name);					
					File f=new File(outputDirectory+File.separator+zipEntry.getName());
					f.createNewFile();
					InputStream in = zipFile.getInputStream(zipEntry);
					FileOutputStream out=new FileOutputStream(f);					
					int c;
					byte[] by=new byte[1024];
					while((c=in.read(by)) != -1){
						out.write(by,0,c);
					}
					out.close();
					in.close();
				}
			}
		}
		catch (Exception ex){
			System.out.println("解压文件异常"+ex.getMessage());
			ex.printStackTrace();
		}
	}
	/**
	 * 创建目录,包括子目录
	 * @param dir
	 * @throws Exception
	 */
	private static void mkDirs(String dir) throws Exception{
		if(dir == null || dir.equals("")) return;
		File f1 = new File(dir);
		if(!f1.exists())
			f1.mkdirs();
	}	


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			extract("D:\\开源项目\\apache\\新建文件夹.zip", "D:\\开源项目\\apache\\aa");
		} catch (Exception e) {			
			e.printStackTrace();
		}
	}

}

 以上代码已经测试通过,支持中文目录、文件名,不限目录级别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值