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(,name.length()-1);
- mkDirs(outputDirectory+File.separator+name);
- //System.out.println("创建目录:"+outputDirectory+File.separator+name);
- }else{
- String name=zipEntry.getName();
- String dir = name.substring(,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,,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();
- }
- }
- }
以上代码已经测试通过,支持中文目录、文件名,不限目录级别。