Java实现ZIP解压功能

1.引入依赖

<dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.9.6</version>
</dependency>

2.Java代码

public class ZipUtils {
    private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);

    /**
     *ZIP文件解压操作类
     * @param path 解压的ZIP源文件路径 必须
     * @param goalPath  解压的目标文件夹路径 非必须
     * @param perFileName   解压文件的文件名前缀 非必须
     * @return  返回解压图片和图片路径
     * @throws Exception
     */
    public static HashMap<String,String> unZip(String path, String goalPath, String perFileName) throws Exception{
        int count = -1;
        int index = -1;
        String savePath = "";
        InputStream in = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        String goal_fileName ="";
        int bufLength  = 1024;
        byte[] b = null;
        HashMap<String,String> fileNameMap = new HashMap<String, String>();
        try {
            logger.debug("--解压缩文件:"+path);
            ZipFile localFile = new ZipFile(path);
            Enumeration<?> entries = localFile.getEntries();
            while(entries.hasMoreElements()){
                byte[] buf = new byte[bufLength];
                ZipEntry tmpEntry = (ZipEntry) entries.nextElement();
                String fileName = tmpEntry.getName();
//              得到文件的扩展名
                String file_ext_name = fileName.substring(fileName.lastIndexOf(".") + 1);

                if(file_ext_name.equals("jpg")||file_ext_name.equals("jpeg")||file_ext_name.equals("png")||file_ext_name.equals("gif")
                        ||file_ext_name.equals("bmp")){
    //              设置文件解压缩目标文件夹
                    if(goalPath!=null&&goalPath.length()!=0){
                        savePath = goalPath+ "/";
                    }else{
                        savePath = path.substring(0, path.lastIndexOf(".")) + "/";
                    }

                    File unZipFile = new File(savePath);
                    if(!unZipFile.exists()){
                        unZipFile.mkdir();
                        logger.debug("--解压缩输出目标文件夹不存在,创建目标文件夹"+savePath);
                    }
//               组装解压的目标文件
                    if(perFileName!=null&&perFileName.length()!=0){
                        goal_fileName = perFileName+"_"+fileName;
                    }else{
                        goal_fileName =  fileName;
                    }
                    // 上传的图片格式
                    fileName = savePath + goal_fileName;
                    logger.debug("--解压文件:"+fileName);

                    File file = new File(fileName);
                    file.createNewFile();
                    in = localFile.getInputStream(tmpEntry);

                    fos = new FileOutputStream(file);
                    bos = new BufferedOutputStream(fos,bufLength);
                    while((count = in.read(buf))>-1){
                        bos.write(buf,0,count);
                    }
                    fileNameMap.put(goal_fileName,fileName);
                    bos.flush();
    //              关闭资源
                    closeResource(bos,fos,in);

    //              如果是gif格式的图片,则生成临时gif文件,并获取gif图片的第一帧
                    if (file_ext_name.trim().equals("gif")|| file_ext_name.trim().equals("GIF")) {
                        logger.debug("####上传的图片格式为:file_ext_name:"+file_ext_name);
                        // 临时文件夹
                        String tmpUrl = goalPath + "/gifTmp";
                        File gifTmpFiles = new File(tmpUrl);
                        if (!gifTmpFiles.exists()) {
                            gifTmpFiles.mkdirs();
                        }

                        // 临时gif图片
                        File gifTmpFile = new File(tmpUrl, goal_fileName);
                        File gifLocalFile = new File(fileName);
                        FileUtil.copyFile(gifLocalFile, gifTmpFile);

                        // 获取gif图片的第一帧
                        try{
                            b = ImageUtils.returnGifFirstByte(gifTmpFile.getAbsolutePath());
                        }catch (Exception e){
                            logger.error("--获取gif图片的第一帧失败",e);
                            throw new Exception(e);
                        }

                        // 删除临时gif图片
                        logger.debug("####删除GIF文件临时文件:gifTmpFile:"+gifTmpFile.getAbsolutePath());
                        gifTmpFile.delete();
                        logger.debug("####删除GIF本地解压文件:gifLocalFile:"+gifLocalFile.getAbsolutePath());
                        //删除原始本地GIF图片
                        gifLocalFile.delete();
                        // 保存原图片
                        if (b == null || b.length <= 0) {
                            logger.error("GIF文件为空,解压失败!"+fileName);
                            throw new Exception("gif fail");
                        }else{

                            fileName = fileName.substring(0,fileName.lastIndexOf("."))+".jpg";
                            logger.debug("####GIF文件转换为本地JPG文件:fileName:"+fileName);
                            FileOutputStream out = new FileOutputStream(fileName);
                            out.write(b);
                            out.close();
                        }
                    }
                    fileNameMap.put(goal_fileName,fileName);
                }else{
                    logger.error("#####文件格式不合法,拒绝解压缩!fileName:"+fileName);
                }

            }
//           删除解压缩文件
                Util.delUrlLocalFile(path);

            try {
                if(localFile!=null){
                    localFile.close();
                }
            } catch (IOException e) {
                logger.error("localFile关闭失败!",e);
                localFile.close();

            }
        } catch (Exception e) {
            logger.error("zip文件解压失败!",e);
            throw new Exception(e);
        }
        return fileNameMap;

    }


    public static void closeResource(BufferedOutputStream bos,FileOutputStream fos,InputStream in){
        try{
            if(bos!=null){
                bos.close();
            }
        }catch(Exception e){
            logger.error("BufferedOutputStream关闭失败!",e);
        }

        try{
            if(fos!=null){
                fos.close();
            }
        }catch(Exception e){
            logger.error("FileOutputStream关闭失败!",e);
        }

        try{
            if(in!=null){
                in.close();
            }
        }catch(Exception e){
            logger.error("inputstream关闭失败!",e);
            }
    }

}

由于涉及的业务是图片的打包文件,代码仅写了图片文件的解压。

posted @ 2016-07-08 15:34  浪荡小新  阅读(528)  评论(0编辑  收藏  举报