压缩文件解压


/**
     * 解压上传文件    
     * @param importZipFilePath
     * 上传文件地址
     * @param importFilePath
     * 解压文件存放地址
     * @param cancel
     * @return
     */
    public Map<String, Object> unCompressFiles(String importZipFilePath,String importFilePath,String cancel){
        Map<String,Object> result = new HashMap<>();
        File importZipFile = new File(importZipFilePath);
        File[] compressFiles = importZipFile.listFiles();
        List<String> list = new ArrayList<>();
        if(!StringUtils.isNull(cancel)){
            String[] params =null;
            if(cancel.indexOf(",")>0){
                params = cancel.split(",");
                list = Arrays.asList(params);
            }else{
                list.add(cancel);
            }
        }
        if(compressFiles !=null && compressFiles.length>0){
            for(File compressFile :compressFiles){
                String fileName = compressFile.getName();
                String realName =  compressFile.getName();
                String filePath = compressFile.getPath();
                if(list.contains(fileName)){
                    continue;
                }
                String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
                if(fileName.toLowerCase().endsWith(".zip") || fileName.toLowerCase().endsWith(".rar")){
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                }
                String unCompressFilePath =importFilePath+separator+fileName;
                File importFile = new File(unCompressFilePath);
                 if(importFile.exists()){
                     FileUtils.deleteDirectory(unCompressFilePath);
                     importFile.mkdirs();
                 }else{
                     importFile.mkdirs();
                 }
                 try {
                    if(fileType.equals("zip")){
                         unZipFile(filePath, unCompressFilePath);
                     }else if(fileType.equals("rar")){
                         unRarFile(filePath, unCompressFilePath);
                     }
                } catch (Exception e) {
                    if(result.isEmpty() || (!result.isEmpty() && result.get("201")==null)){
                        result.put("201", realName+":上传文件已损坏。");
                    }else{
                        result.put("201", realName+"、"+result.get("201"));
                    }
                    FileUtils.deleteDirectory(unCompressFilePath);
                }finally{
                    System.gc();
                    FileUtils.deleteDirectory(filePath);
                }
            }
        }else{
            result.put("500", "文件上传失败。");
        }
        if(result !=null && result.size()>0){
            return result;
        }
        return null;
        
    }





/**
     * @decription 解压zip文件。
     * @param zipfile
     * @param descDir
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFile(String zipPath, String descDir){
        org.apache.tools.zip.ZipFile zipFile = null;
        InputStream in = null;
        FileOutputStream out = null;
        try{
            zipFile = new org.apache.tools.zip.ZipFile(zipPath);
            Enumeration e = zipFile.getEntries();
            org.apache.tools.zip.ZipEntry zipEntry = null;
            while(e.hasMoreElements()){
                zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
                if (zipEntry.isDirectory()) {
                     String name = zipEntry.getName();
                     name = name.substring(0, name.length() - 1);
                     File f = new File(descDir + File.separator + name);
                     f.mkdir();
                }else{
                     String fileName = zipEntry.getName();
                     fileName = fileName.replace('\\', '/');
                     if (fileName.indexOf("/") != -1) {
                          createDirectory(descDir, fileName.substring(0,fileName.lastIndexOf("/")));
                          fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName
                              .length());
                     }
                     File f = new File(descDir + separator+ zipEntry.getName());
                     f.createNewFile();
                     in = zipFile.getInputStream(zipEntry);
                     out = new FileOutputStream(f);
        
                     byte[] by = new byte[1024];
                     int c;
                     while ((c = in.read(by)) != -1) {
                      out.write(by, 0, c);
                     }
                }
           }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.gc();
            FileUtils.deleteDirectory(zipPath);
        }
    }





     /**
      * 创建目录
      * @param directory
      * 父目录
      * @param subDirectory
      * 子目录
      */
    private static void createDirectory(String directory, String subDirectory) {
        String dir[];
        File file = new File(directory);
        if(subDirectory == "" && file.exists() != true){
            file.mkdir();
        }else if (subDirectory != ""){
           dir = subDirectory.replace('\\', '/').split("/");
           for (int i = 0; i < dir.length; i++) {
                File subFile = new File(directory + separator + dir[i]);
                if (subFile.exists() == false){
                    subFile.mkdir();
                }
                directory += separator + dir[i];
           }
        }
    }




    /**
     * 根据原始rar路径,解压到指定文件夹下.      
     * @param srcRarPath 原始rar路径
     * @param dstDirectoryPath 解压到的文件夹    
     */
     public static void unRarFile(String srcRarPath, String dstDirectoryPath){
         Archive archive = null;
         FileOutputStream os = null;
         try{
             archive = new Archive(new File(srcRarPath));
         if (archive != null) {
             //a.getMainHeader().print(); // 打印文件信息.
             FileHeader fh = archive.nextFileHeader();
             while(fh != null) {
                      //防止文件名中文乱码问题的处理
                 String fileName = fh.getFileNameW().isEmpty()?fh.getFileNameString():fh.getFileNameW();
                 if(fh.isDirectory()){ // 文件夹
                     File fol = new File(dstDirectoryPath + separator + fileName);
                     fol.mkdirs();
                 }else{ // 文件
                     File out = new File(dstDirectoryPath + separator + fileName.trim());
                     if(!out.exists()){
                         if(!out.getParentFile().exists()){// 相对路径可能多级,可能需要创建父目录.
                             out.getParentFile().mkdirs();
                         }
                         out.createNewFile();
                     }
                     os = new FileOutputStream(out);
                     archive.extractFile(fh, os);
                 }
                 fh = archive.nextFileHeader();
             }
            
         }
         }catch  (Exception ex) {
             ex.printStackTrace();
         }finally{
             if(archive !=null){
                 try {
                    archive.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             }
             if(os !=null){
                 try {
                     os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             }
             System.gc();
             FileUtils.deleteDirectory(srcRarPath);
         }
     }

posted on 2017-07-26 08:50  天生一对  阅读(276)  评论(0编辑  收藏  举报

导航