java删除指定目录中的文件或文件夹

原创
2014/12/24 11:11
阅读数 269

java删除指定目录中的文件或文件夹

package tf;

import java.io.File;

public class DelFile {

	public static void main(String[] args) {
		scanAllFile(new File("E:/ACD2.0"), "svn", ".dat", ".vvb");
		System.out.println("delete success!");
	}

	/**
	 * @author 唐飞
	 * @function 扫描待删除的目录或文件
	 * @root 待扫描的根目录
	 * @suffix 待删除的目录或文件(扩展名匹配)
	 */
	public static void scanAllFile(File root, String... suffix) {
		for (File file : root.listFiles()) {
			if (isMatch(file.getName(), suffix)) {
				delAllFile(file);
			} else if (file.isDirectory()) {
				scanAllFile(file, suffix);
			}
		}
	}

	// 判断是否为待删除的目录或文件
	public static boolean isMatch(String name, String... suffix) {
		for (String s : suffix) {
			if (name.endsWith(s)) {
				return true;
			}
		}
		return false;
	}

	// 删除指定的目录或文件
	public static void delAllFile(File file) {
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				if (!f.delete()) {
					delAllFile(f);
				}
			}
		}
		file.delete();
		System.out.println("delete : " + file.getAbsolutePath());
	}
}
 
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部