java 压缩解压文件

  1 /**
  2  *2007-12-26
  3  */
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.OutputStream;
 10 import java.util.Enumeration;
 11 
 12 import org.apache.tools.zip.ZipEntry;
 13 import org.apache.tools.zip.ZipFile;
 14 import org.apache.tools.zip.ZipOutputStream;
 15 
 16 /**
 17  * ZIP文件压缩和解压(要使用apache ant.jar以处理中文乱码)
 18  * 
 19  * @author sunjun
 20  * @version 2.0
 21  */
 22 public class ZipUtil {
 23 
 24  /**
 25   * 压缩文件file成zip文件zipFile
 26   * 
 27   * @param file
 28   *            要压缩的文件
 29   * @param zipFile
 30   *            压缩文件存放地方
 31   * @throws Exception
 32   */
 33  public static void zip(File file, File zipFile) throws Exception {
 34   ZipOutputStream output = null;
 35   try {
 36    output = new ZipOutputStream(new FileOutputStream(zipFile));
 37    // 顶层目录开始
 38    zipFile(output, file, "");
 39   } catch (Exception ex) {
 40    ex.printStackTrace();
 41   } finally {
 42    // 关闭流
 43    if (output != null) {
 44     output.flush();
 45     output.close();
 46    }
 47   }
 48  }
 49 
 50  /**
 51   * 压缩文件为zip格式
 52   * 
 53   * @param output
 54   *            ZipOutputStream对象
 55   * @param file
 56   *            要压缩的文件或文件夹
 57   * @param basePath
 58   *            条目根目录
 59   * @throws IOException
 60   */
 61  private static void zipFile(ZipOutputStream output, File file,
 62    String basePath) throws IOException {
 63   FileInputStream input = null;
 64   try {
 65    // 文件为目录
 66    if (file.isDirectory()) {
 67     // 得到当前目录里面的文件列表
 68     File list[] = file.listFiles();
 69     basePath = basePath + (basePath.length() == 0 ? "" : "/")
 70       + file.getName();
 71     // 循环递归压缩每个文件
 72     for (File f : list)
 73      zipFile(output, f, basePath);
 74    } else {
 75     // 压缩文件
 76     basePath = (basePath.length() == 0 ? "" : basePath + "/")
 77       + file.getName();
 78     // System.out.println(basePath);
 79     output.putNextEntry(new ZipEntry(basePath));
 80     input = new FileInputStream(file);
 81     int readLen = 0;
 82     byte[] buffer = new byte[1024 * 8];
 83     while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1)
 84      output.write(buffer, 0, readLen);
 85    }
 86   } catch (Exception ex) {
 87    ex.printStackTrace();
 88   } finally {
 89    // 关闭流
 90    if (input != null)
 91     input.close();
 92   }
 93  }
 94 
 95  /**
 96   * 解压zip文件
 97   * 
 98   * @param zipFilePath
 99   *            zip文件绝对路径
100   * @param unzipDirectory
101   *            解压到的目录
102   * @throws Exception
103   */
104  public static void unzip(String zipFilePath, String unzipDirectory)
105    throws Exception {
106   // 定义输入输出流对象
107   InputStream input = null;
108   OutputStream output = null;
109   try {
110    // 创建文件对象
111    File file = new File(zipFilePath);
112    // 创建zip文件对象
113    ZipFile zipFile = new ZipFile(file);
114    // 创建本zip文件解压目录
115    String name = file.getName().substring(0,
116      file.getName().lastIndexOf("."));
117    File unzipFile = new File(unzipDirectory + "/" + name);
118    if (unzipFile.exists())
119     unzipFile.delete();
120    unzipFile.mkdir();
121    // 得到zip文件条目枚举对象
122    Enumeration zipEnum = zipFile.getEntries();
123    // 定义对象
124    ZipEntry entry = null;
125    String entryName = null, path = null;
126    String names[] = null;
127    int length;
128    // 循环读取条目
129    while (zipEnum.hasMoreElements()) {
130     // 得到当前条目
131     entry = (ZipEntry) zipEnum.nextElement();
132     entryName = new String(entry.getName());
133     // 用/分隔条目名称
134     names = entryName.split("\\/");
135     length = names.length;
136     path = unzipFile.getAbsolutePath();
137     for (int v = 0; v < length; v++) {
138      if (v < length - 1) // 最后一个目录之前的目录
139       FileUtil.createDirectory(path += "/" + names[v] + "/");
140      else { // 最后一个
141       if (entryName.endsWith("/")) // 为目录,则创建文件夹
142        FileUtil.createDirectory(unzipFile
143          .getAbsolutePath()
144          + "/" + entryName);
145       else { // 为文件,则输出到文件
146        input = zipFile.getInputStream(entry);
147        output = new FileOutputStream(new File(unzipFile
148          .getAbsolutePath()
149          + "/" + entryName));
150        byte[] buffer = new byte[1024 * 8];
151        int readLen = 0;
152        while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1)
153         output.write(buffer, 0, readLen);
154       }
155      }
156     }
157    }
158   } catch (Exception ex) {
159    ex.printStackTrace();
160   } finally {
161    // 关闭流
162    if (input != null)
163     input.close();
164    if (output != null) {
165     output.flush();
166     output.close();
167    }
168   }
169  }
170 
171  /**
172   * 测试
173   * 
174   * @param args
175   * @throws Exception
176   */
177  public static void main(String[] args) throws Exception {
178   unzip("d:/桌面.zip", "f:/");
179   System.out.println("over....................");
180   zip(new File("C:/a"), new File("d:/桌面.zip"));
181   System.out.println("over..............");
182  }
183 
184 }

from:http://www.oschina.net/code/snippet_101477_1212

posted @ 2012-10-12 10:22  daveztong  阅读(300)  评论(0编辑  收藏  举报