java中zip文件工具类



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipFile;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtil {

 /**
     * 创建ZIP文件
     * @param sourcePath 文件或文件夹路径
     * @param zipPath 生成的zip文件存在路径(包括文件名)
  * @throws IOException
     */
    public static void downloadZip(String sourcePath,HttpServletResponse response) throws IOException {
     String zipName = sourcePath.substring(sourcePath.lastIndexOf("/")+1);
     response.setContentType("application/x-zip-compressed");
     response.setHeader("Content-Disposition", "attachment;filename=" + zipName +".zip");
        LogUtil.trace("创建ZIP文件开始"+sourcePath);
        ZipOutputStream zos = null;
       
        try {
            zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zos.setEncoding("gbk");
            writeZip(new File(sourcePath), "", zos);
        } catch (FileNotFoundException e) {
         LogUtil.error("创建ZIP文件失败:"+ ExceptionUtils.getStackTrace(e));
         throw new FileNotFoundException(" 创建ZIP文件失败");
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
            } catch (IOException e) {
             LogUtil.error("创建ZIP文件失败:"+ ExceptionUtils.getStackTrace(e));
            }

        }
    }

    private static void writeZip(File file, String parentPath, ZipOutputStream zos) throws IOException {
     LogUtil.trace("下载zip开始");
     if(file.exists()){
      LogUtil.trace("下载zip开始 -- 文件存在");
            if(file.isDirectory()){//处理文件夹
             if(!file.getName().equals(DateUtil.formatSystimeToString8())){
              parentPath+=file.getName()+File.separator;//下载路径去除年月日那一层
             }
             LogUtil.trace("下载zip开始parentPath ="+ parentPath);
                File [] files=file.listFiles();
                for(File f:files){
                    writeZip(f, parentPath, zos);
                }
            }else{
                FileInputStream fis=null;
                DataInputStream dis=null;
                try {
                 LogUtil.trace("创建ZIP文件 == 开始写入");
                    fis = new FileInputStream(file);
                    dis = new DataInputStream(new BufferedInputStream(fis));
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte [] content=new byte[1024];
                    int len;
                    while((len=fis.read(content))!=-1){
                        zos.write(content,0,len);
                        zos.flush();
                    }

                } catch (FileNotFoundException e) {
                 LogUtil.error("创建ZIP文件失败"+ ExceptionUtils.getStackTrace(e));
                 throw new FileNotFoundException(" 创建ZIP文件失败!");
                } catch (IOException e) {
                 LogUtil.error("创建ZIP文件失败"+ ExceptionUtils.getStackTrace(e));
                 throw new IOException(" 创建ZIP文件失败!");
                }finally{
                    try {
                        if(dis!=null){
                            dis.close();
                        }
                    }catch(IOException e){
                     LogUtil.error("流关闭失败"+ ExceptionUtils.getStackTrace(e));
                    }
                }
            }
        }
    }
 
   
    /**
    * 解压ZIP文件
    * @param zipFile  要解压的ZIP文件路径
    * @param destPath  解压目标路径
    * @throws IOException
    */
 public static void unzip(String zipFile, String destPath) throws Exception {
  ZipFile zip = null;
  ZipEntry entry = null;
  byte[] buffer = new byte[8192];
  int length = -1;
  InputStream input = null;
  BufferedOutputStream bos = null;
  File file = null;
  try {
   zip = new ZipFile(zipFile);
   Enumeration en = zip.entries();
   while (en.hasMoreElements()) {
    entry = (ZipEntry) en.nextElement();
    if (entry.isDirectory()) {
     continue;
    }
    input = zip.getInputStream(entry);
    file = new File(destPath, entry.getName());
    if (!file.getParentFile().exists()) {
     file.getParentFile().mkdirs();
    }
    bos = new BufferedOutputStream(new FileOutputStream(file));
    while (true) {
     length = input.read(buffer);
     if (length == -1) {
      break;
     }
     bos.write(buffer, 0, length);
    }
    bos.close();
    input.close();
   }
   zip.close();
  } catch (Exception ex) {
   ex.printStackTrace();
   throw new Exception("ZipUtil unzip-解压缩文件抛异常 :" + ExceptionUtils.getStackTrace(ex));
  } finally {
   try {
    if (bos != null)
     bos.close();
    if (input != null)
     input.close();
    if (zip != null)
     zip.close();
   } catch (IOException e) {
    throw new Exception("ZipUtil unzip-解压缩文件关闭流抛异常 :" + ExceptionUtils.getStackTrace(e));
   }
  }
  
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值