java解压zip、rar(多级文件)

/**
     * 解压上传文件    
     * @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];
           }
        }
    }
    /**
     * @author Hanhh
     * @data 2016-11-02
     * 根据原始rar路径,解压到指定文件夹下.      
     * @param srcRarPath 原始rar路径
     * @param dstDirectoryPath 解压到的文件夹      
     * @throws IOException
     * @throws RarException
     */
     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);
         }
     }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值