您的位置:首页 > 编程语言 > Java开发

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

2014-10-25 18:12 1116 查看
作者:张昌昌

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

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)如何解压文件

转载请说明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: