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

Java递归删除目录文件

2015-07-03 10:02 639 查看
package com.jiepu.copy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Java递归删除目录文件
* @author Administrator
*
*/
public class FileSystem {

public static void main(String[] args) {

long a = System.currentTimeMillis();
List<File> resultfiles = new ArrayList<File>();

String[] lists = { "I:\\IT\\图标图片素材大全" };

for (int i = 0; i < lists.length; i++) {
File file = new File(lists[i]);

List<String> endWithTypes=new ArrayList<String>();
endWithTypes.add("rar");
endWithTypes.add("zip");
endWithTypes.add("7z");
endWithTypes.add("iso");
endWithTypes.add("bmp");
endWithTypes.add("png");
endWithTypes.add("jpg");
endWithTypes.add("gif");
endWithTypes.add("ico");
endWithTypes.add("jpeg");

scanDirRecursion(file, resultfiles,endWithTypes);
}
for (File file : resultfiles) {
//System.out.println(file.getAbsolutePath());
}

System.out.print("文件总数:" + resultfiles.size());
System.out.print("总耗时:");
System.out.println((System.currentTimeMillis() - a) + "ms");
System.out.println((System.currentTimeMillis() - a) / 1000 + "s");
}

/**
* 递归遍历目录
*
* @param file
*            文件目录
* @param resultfiles
*            保存返回的结果集
* @param endWith
*            为null,则返回所有文件,不为空,则返回所匹配的文件
*/
public static void scanDirRecursion(File file, List<File> resultfiles,
List<String> endWithTypes) {
try {
if (file.canRead()) {
if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
scanDirRecursion(new File(file, files[i]),
resultfiles, endWithTypes);
}
}
} else {
// System.out.println(file);
if (endWithTypes != null) {
boolean isendWith=false;
for(String endWith:endWithTypes)
{
if (file.getName().toLowerCase().endsWith(endWith.toLowerCase()))
{
resultfiles.add(file);
isendWith=true;
}

}
if(isendWith==false)
{
System.out.println("file del "+file.getAbsolutePath());
file.delete();
}

} else {
resultfiles.add(file);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

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