码迷,mamicode.com
首页 > 编程语言 > 详细

java获取递归获取嵌套压缩包(zip和rar)中的所有文件

时间:2014-10-25 18:48:36      阅读:438      评论:0      收藏:0      [点我收藏+]

标签:java   获取压缩包文件   广度优先遍历   深度优先遍历   递归调用   

          作者:张昌昌

         为了获取一个压缩包中的文件,而该压缩包里可能又含有压缩包 、文件夹、文件夹里又包含压缩包、文件等各种嵌套的情况,采用广度优先遍历和深度优先遍历的方法解决了此问题。

public static List<File> getFilesOfZipAndRar(String zipPath) throws IOException
     {
      String destPath = zipPath.substring(0,zipPath.lastIndexOf(".")) + "/";
      //先将该压缩文件解压
      if(zipPath.contains(".zip"))
       unZipFile(new File(zipPath),destPath);
      if(zipPath.contains(".rar"))
       unRarFile(new File(zipPath),destPath);
      //进入解压目录,将该目录的所有zip都解压
      recursiveCompressedFile(new File(destPath));
      //得到该目录下的所有文件
      Iterator iterator = Directory.walk(destPath).iterator();
         List<File> files = new ArrayList<File>();
         File file = null;
         while(iterator.hasNext())
         {
          file = (File)iterator.next();
          if(file.getName().contains(".rar"))
           continue;
          files.add(file);
         }
         return files;
     }
    
     public static void recursiveCompressedFile(File file) throws IOException
     {
      //广度优先遍历
      for(File e:file.listFiles())
      {
       String filePath = e.getAbsolutePath().replace("\\\\","/");
       //深度优先遍历
       if(e.getName().contains(".zip"))
       {
        String desString = filePath.substring(0,filePath.lastIndexOf("."))+"/";
        unZipFile(e,desString);
        e.delete();
        recursiveCompressedFile(new File(desString));
       }
       if(e.getName().contains(".rar"))
       {
        String desString = filePath.substring(0,filePath.lastIndexOf("."))+"/";
        unRarFile(e,desString);
        e.delete();
        recursiveCompressedFile(new File(desString));
       }
       if(e.isDirectory())
        recursiveCompressedFile(e);
      }
     }

总结:该问题的解决过程中学习了:(1)广度优先和深度优先的策略;(2)递归调用的方法;(3)如何解压文件

转载请说明出处。

java获取递归获取嵌套压缩包(zip和rar)中的所有文件

标签:java   获取压缩包文件   广度优先遍历   深度优先遍历   递归调用   

原文地址:http://blog.csdn.net/zcc_0015/article/details/40454777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!