博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java的zip压缩
阅读量:6876 次
发布时间:2019-06-26

本文共 4794 字,大约阅读时间需要 15 分钟。

hot3.png

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
> zipEntryList) throws IOException{        return zipCompress(zipEntryList, null);    }        /**     * 生成压缩文件|ByteArrayOutputStream不能用这个     * @param zipEntryList     * @param comment 注释     * @return     * @throws IOException     */    public static byte[] zipCompress(List
> 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
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
assembleZipEntryMap(ZipEntry ze,InputStream baosIn){        Map
zipEntryMap=new HashMap
();        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
> zipEntryList=new ArrayList
>();        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

你可能感兴趣的文章
OpenSSH配置文件详解
查看>>
IE浏览器中 $.ajax返回uindefined 其他浏览器正常
查看>>
docker+dockerfly管理端
查看>>
ELK安装
查看>>
mysql之innodb的mvcc多版本控制
查看>>
使用 LogStash 归集日志
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
德国博世百年风雨启示录(下):实业强国
查看>>
(整理)用Elixir做一个多人扑克游戏 4
查看>>
关于架构
查看>>
The application’s PagerAdapter changed the adapter’s contents without calling PagerA
查看>>
qcom 跨平台的串口调试工具 PKGBUILD
查看>>
Delphi 时间格式化,动态显示时间,显示最新时间
查看>>
在JAVA中将NEW一分为2,分步进行[反射机制产生类]
查看>>
Java多态性的两个特殊情况
查看>>
我的友情链接
查看>>
怎么改变Win7登陆背景图片
查看>>
虚拟带库和物理带库比较
查看>>
AD委派加域权限
查看>>