Java递归删除目录文件

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();
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值