java的zip压缩

package xxx.xxx.common.zip;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 生成zip压缩包的工具类
 * @author yfx
 */
public class ZipUtils {
    
    public static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
    
    /**
     * 生成压缩文件
     * @param zipEntryList
     * @return
     * @throws IOException
     */
    public static byte[] zipCompress(List<Map<String,Object>> zipEntryList) throws IOException{
        return zipCompress(zipEntryList, null);
    }
    
    /**
     * 生成压缩文件|ByteArrayOutputStream不能用这个
     * @param zipEntryList
     * @param comment 注释
     * @return
     * @throws IOException
     */
    public static byte[] zipCompress(List<Map<String,Object>> zipEntryList,String comment) throws IOException{
        String temPath=getFilePath();
        String zipFilePath = temPath + gen() + ".zip";
        File srcFile=new File(zipFilePath);
        ZipOutputStream zipOutputStream =new ZipOutputStream(srcFile);
        zipOutputStream.setEncoding("UTF-8");
        if(zipEntryList!=null&&zipEntryList.size()>0){
            for(Map<String,Object> zipEntryMap:zipEntryList){
                ZipEntry en=(ZipEntry)zipEntryMap.get("zipEntry");
                InputStream baosIn=(InputStream)zipEntryMap.get("inputStream");
                zipCompress(zipOutputStream, en, baosIn);
            }
        }
        if(StringUtils.isNotBlank(comment)){
            setComment(zipOutputStream, comment);
        }
        try {
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (IOException e) {}
        try {
            byte[] data=FileUtils.readFileToByteArray(srcFile);
            FileUtils.forceDelete(srcFile);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 向压缩文件中装入文件
     * @param zipOutputStream
     * @param en
     * @param baosIn
     * @throws IOException
     */
    public static void zipCompress(ZipOutputStream zipOutputStream,ZipEntry en,InputStream baosIn) throws IOException{
        zipOutputStream.putNextEntry(en);  
        int len=0;  
        byte[]buffer=new byte[1024];  
        while(-1!=(len=baosIn.read(buffer))){  
            zipOutputStream.write(buffer, 0, len);  
        }  
        zipOutputStream.flush();
        try{
            baosIn.close();  
        }catch(IOException e){}
    }
    
    /**
     * 组装压缩文件全信息map
     * @param ze
     * @param baosIn
     * @return
     */
    public static Map<String,Object> assembleZipEntryMap(ZipEntry ze,InputStream baosIn){
        Map<String,Object> zipEntryMap=new HashMap<String,Object>();
        zipEntryMap.put("zipEntry", ze);
        zipEntryMap.put("inputStream", baosIn);
        return zipEntryMap;
    }
    
    /**
     * 组装压缩文件信息
     * @param fileName
     * @param fileLength
     * @return
     */
    public static ZipEntry assembleZipEntry(String fileName,Long fileLength){
        ZipEntry en=new ZipEntry(new String(fileName));  
        en.setSize(fileLength);
        return en;
    }
    
    /**
     * 写入注释
     * @param zipOutputStream
     * @param comment
     */
    public static void setComment(ZipOutputStream zipOutputStream,String comment){
        zipOutputStream.setEncoding("GBK");
        zipOutputStream.setComment(comment);
    }
    
    /**
     * 得到md5值
     * @param datas
     * @return
     */
    public static String getMD5(byte[] datas){
        String str=DigestUtils.md5Hex(datas);
        return str;
    }
    
    /**
     * 得到md5值
     * @param is
     * @return
     * @throws IOException
     */
    public static String getMD5(InputStream is) throws IOException{
        String str=DigestUtils.md5Hex(is);
        return str;
    }
    
    public static String gen(){
        return java.util.UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
    }
    
    /**
     * 得到一个本地当前路径
     * @return
     */
    public static String getFilePath() {
        File file = new File(".");
        String savePath = null;
        try {
            savePath = file.getCanonicalPath().replace("bin", "temp");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        if (null != savePath && (!savePath.endsWith("\\") || !savePath.endsWith("/"))) {
            savePath += "/";
        }
        return savePath;
    }
    
    public static void main(String[] args) throws IOException {
        byte[] bytePdf=FileUtils.readFileToByteArray(new File("/test.pdf"));
        ByteArrayInputStream bais=new ByteArrayInputStream(bytePdf);
        
        List<Map<String,Object>> zipEntryList=new ArrayList<Map<String,Object>>();
        zipEntryList.add(assembleZipEntryMap(assembleZipEntry("我的文件/test.pdf",new Long( bytePdf.length)),bais));
        byte[] data=zipCompress(zipEntryList);
        FileUtils.writeByteArrayToFile(new File("/test.zip"), data);
    }
}

zip里的文件夹是自动创建的。

转载于:https://my.oschina.net/yifanxiang/blog/760407

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值