package test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SweepUnusedFiles
{
    public static void main(String[] args)
    {
        String filedir = "F:\\某个目录下";
        List suffixList = new ArrayList();
        suffixList.add(".db");
        // suffixList.add(".tmp");
        // suffixList.add(".html_zh");
        // suffixList.add("_zh.js");

        SweepUnusedFiles sweepUnusedFiles = new SweepUnusedFiles();
        sweepUnusedFiles.startDeleteFixedFiles(filedir, suffixList);
        System.out.println("执行完成!");
    }

    public void startDeleteFixedFiles(String filedir, List suffixList)
    {
        if (null == filedir || "".equals(filedir.trim()))
        {
            System.out.println("filedir 目录不对!");
            return;
        }
        filedir = filedir.trim();

        if (null == suffixList || suffixList.size() <= 0)
        {
            System.out.println("suffixList 没有要匹配的后缀!");
            return;
        }

        File f = new File(filedir);
        if (f.isDirectory())
        {
            handleFile(f, suffixList);
        }
        else
        {
            System.out.println("filedir 必须为目录");
            /* for (String suffix : suffixList) { if (f.getName().endsWith(suffix)) { // 匹配到的要删除 try { f.delete(); }
             * catch (Exception e) { System.out.println("文件删除失败:" + f.getAbsolutePath() + "\\" + f.getName()); } } } */
        }
    }

    private void handleFile(File filedir, List suffixList)
    {
        // 目录
        File[] files = filedir.listFiles();
        for (File subFile : files)
        {
            if (subFile.isDirectory())
            {
                handleFile(subFile, suffixList);
            }
            else
            {
                // 文件
                for (String suffix : suffixList)
                {
                    if (subFile.getName().endsWith(suffix))
                    {
                        // 匹配到的要删除
                        try
                        {
                            subFile.delete();
                            System.out.println("已删除文件:" + subFile.getAbsolutePath() + "\\" + subFile.getName());
                        }
                        catch (Exception e)
                        {
                            System.out.println("文件删除失败:" + subFile.getAbsolutePath() + "\\" + subFile.getName());
                        }
                    }
                }
            }
        }

    }

}