文件解压缩操作

来源:互联网 发布:淘宝如何拍下商品 编辑:程序博客网 时间:2024/05/01 09:37

/**
 * 文件解压缩操作
 */
package com.general.system;

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

/**

 * 参考:http://henterji.blogbus.com/logs/2005/12/2034091.html
 */

public class UndoZip {


 protected ZipFile zippy;
 protected byte[] b;
 
 UndoZip() {
  b = new byte[8092];
 }
 
 protected SortedSet dirsMade;
 
 public void unZip(String theOldPath,String theNewPath,String fileName) {
  dirsMade = new TreeSet();
  try {
   theOldPath = theOldPath.replaceAll("////","/");
   theNewPath = theNewPath.replaceAll("////","/");
   if(!theOldPath.endsWith("/")){
    theOldPath = theOldPath+"/";
   }
   if(!theNewPath.endsWith("/")){
    theNewPath = theNewPath+"/";
   }
   
   zippy = new ZipFile(theOldPath+fileName);
   Enumeration all = zippy.entries();
   while (all.hasMoreElements()) {
    getFile(theNewPath,(ZipEntry) all.nextElement());
   }
  }
  catch (IOException err) {
   System.err.println("IO Error: " + err);
   return;
  }
 }
 
 protected boolean warnedMkDir = false;
 
 @SuppressWarnings("unchecked")
 protected void getFile(String theNewPath,ZipEntry e) throws IOException {
  
  String zipName = theNewPath+e.getName();
  if (zipName.startsWith("/")) {
   if (!warnedMkDir){
    System.out.println("Ignoring absolute paths");
   }
   warnedMkDir = true;
   zipName = zipName.substring(1);
  }
  if (zipName.endsWith("/")) {
   return;
  }
  
  int ix = zipName.lastIndexOf('/');
  if (ix> 0) {
   String dirName = zipName.substring(0, ix);
   if (!dirsMade.contains(dirName)) {
    File d = new File(dirName);
    if (!(d.exists()&& d.isDirectory())) {
     if (!d.mkdirs()) {
      System.err.println("Warning: unable to mkdir "+ dirName);
     }
     dirsMade.add(dirName);
    }
   }
  }
  
  FileOutputStream os = new FileOutputStream(zipName);
  InputStream is = zippy.getInputStream(e);
  int n = 0;
  while ((n = is.read(b))> 0) {
   os.write(b, 0, n);
  }
  is.close();
  os.close();
 }
 /*
 public static void main(String[] args) {
  String theOldPath = "D:/My_item/CMS.war/WEB-INF/classes/com/general/system/test/";
  String theNewPath = "D:/ok/";
  UndoZip u = new UndoZip();
  u.unZip(theOldPath,theNewPath,"using.zip");
 }*/
}


 

原创粉丝点击