1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Java获取压缩包内文件数_java获取递归获取嵌套压缩包(zip和rar)中的所有文件

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

时间:2020-09-10 21:10:44

相关推荐

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

作者:张昌昌

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

public static List 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 files = new ArrayList();

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

转载请说明出处。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。