潇洒郎: java 实现删除文件夹下文件与子文件下的所有文件,并实现文件过滤,可排除特殊后缀文件,实现排除或者删除文件时有名称的文件优先后缀类型文件

文件过滤配置

file-cleanup.exclude=.log;script;test3.zip;a.txt;
file-cleanup.include=useless.log;execute.log;.txt

实现删除useless.log;execute.log;, 同时保留a.txt

递归获取文件夹下的所有文件与子文件中的文件

private static void cleanupFilesWork(JobDataMap map) {
        String dirPath = (String) map.get("dirPath");
        if (strOK(dirPath)) { // 有效性判断
            List dirList = splitCheckTrimStr(dirPath, ";");
            if (dirList.size()>0) {
                String minusDays = (String) map.get("minusDays");
                String exclude = (String) map.get("exclude");
                String include = (String) map.get("include");
                // 获取当前时间
                LocalDateTime currentTime = LocalDateTime.now();
                // 计算X天前的时间
                long secondMinus = (long) (Float.parseFloat(minusDays)*24*3600);
                //LocalDateTime oneDayAgo = currentTime.minusDays(minus);
                LocalDateTime oneDayAgo = currentTime.minusSeconds(secondMinus);
                log.info("删除{}秒 {}之前的文件", secondMinus, oneDayAgo);
                // 将LocalDateTime转换为FileTime
                FileTime fileTime = FileTime.from(oneDayAgo.atZone(ZoneId.systemDefault()).toInstant());

                // 处理过滤字符串
                List excludeList = splitCheckTrimStr(exclude, ";");
                List includeList = splitCheckTrimStr(include, ";");
                for(String dir: dirList) {
                    delAllFiles(dir, fileTime, includeList, excludeList);
                    delAllEmptyDir(dir, null);
                }
            }
        }
    }

    private static void delAllFiles(String folderPath, FileTime fileTime, List includeList, List excludeList) {
        for (File file : getAllFiles(folderPath)) {
            // 判断文件的最后修改时间是否符合条件
            if (file.lastModified() < fileTime.toMillis()) {
                if (fileFilter(file, includeList, excludeList)) {
                    // 删除文件
                    file.delete();
                    log.info("清理文件"+ file.getAbsolutePath()+ "成功");
                } else {
                    log.info("不删除过滤文件{}", file.getName());
                }
            }
        }
    }


    public static Map judgeInExclude(File file, List list) {
        Map map = new HashMap();
        String st = null;
        boolean mather = false;
        if (!list.isEmpty()) {
            for(String str: list) {
                if (file.getAbsolutePath().contains(str)) {
                    st = str;
                    mather = true;
                    break;
                }
            }
        }
        map.put(st, mather);
        return map;
    }

    /**
     * 字符串分割处理,检查
     * @param exclude
     * @param sp
     * @return
     */
    public static List splitCheckTrimStr(String exclude, String sp) {
        String[] excludes = exclude.split(sp);
        List excludeList = new ArrayList();
        for(String str: excludes) {
            if (strOK(str)) {
                excludeList.add(str.trim());
            }
        }
        return excludeList;
    }

    public static boolean strOK(String str) {
        if (str==null) {
            return false;
        } else {
            str = str.trim();
            return str.length() > 1;
        }
    }


    public static void delAllEmptyDir(String folderPath, FileTime fileTime) {
        for (File file : getAllDirs(folderPath)) {
            delDir(file, fileTime);
        }
    }

    /**
     * 获取指定文件夹中所有文件,包括子文件夹中的文件
     * @param folderPath 文件夹路径
     * @return 文件列表
     */
    public static List getAllFiles(String folderPath) {
        List fileList = new ArrayList<>();
        File folder = new File(folderPath);
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        fileList.add(file);
                    } else if (file.isDirectory()) {
                        fileList.addAll(getAllFiles(file.getAbsolutePath()));
                    }
                }
            }
        }
        return fileList;
    }

    public static void delDir(File root, FileTime fileTime) {
        if (root!=null) if (isEmpty(root)) {
            if (fileTime!=null) {
                if (root.lastModified() < fileTime.toMillis()) {
                    // 删除文件
                    root.delete();
                    log.info("清理空目录"+ root.getAbsolutePath()+ "成功");
                }
            } else {
                root.delete();
                log.info("清理空目录"+ root.getAbsolutePath()+ "成功");
            }
            delDir(root.getParentFile(), fileTime);
        } else {
            delDir(root.getParentFile(), fileTime);
        }
    }

    public static boolean isEmpty(File file) {
        if (file!=null) {
            if (file.isDirectory() && (file.list().length==0)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取指定文件夹中所有子文件夹
     * @param folderPath 文件夹路径
     * @return 子文件夹列表
     */
    public static List getAllDirs(String folderPath) {
        List fileList = new ArrayList<>();
        File folder = new File(folderPath);
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        continue;
                    } else if (file.isDirectory()) {
                        fileList.addAll(getAllDirs(file.getAbsolutePath()));
                    }
                }
            } else {
                fileList.add(folder);
            }
        }
        return fileList;
    }

    public static boolean fileFilter(File file, List includeList, List excludeList) {
        // 主旨是删除文件
        //log.info("文件路径为:{}", file.getName());
        boolean isDelete = true; // 默认删除文件
        boolean matherExclude = false;
        boolean matherInclude = false;
        String strExclude = null; // 符合条件时的字符串
        String strInclude = null; // 符合条件时的字符串
        Map incMap = judgeInExclude(file, includeList);
        Map excMap = judgeInExclude(file, excludeList);
        for(Map.Entry entry : incMap.entrySet()) {
            strInclude = (String) entry.getKey();
            matherInclude = (boolean) entry.getValue();
        }
        for(Map.Entry entry : excMap.entrySet()) {
            strExclude = (String) entry.getKey();
            matherExclude = (boolean) entry.getValue();
        }
        //log.info("排除状态={}, str={}, 删除状态={}, str={}", matherExclude, strExclude, matherInclude, strInclude);
        if (matherInclude!=matherExclude) { //
            if (matherInclude) {
                isDelete = true;
            }
            if (matherExclude) {
                isDelete = false;
            }
        } else if (matherInclude && matherExclude) { //均匹配上, 矛盾, str不同, 对名称进行判断
            // 名称优先,删除优先 排除状态=true, str=a.txt, 删除状态=true, str=.txt
            if (!(strInclude.charAt(0)=='.')) { // strInclude有名称, 必删除
                isDelete = true;
            } else { // strInclude无名称
                if (!(strExclude.charAt(0)=='.')) { // 有名称, 不删除
                    isDelete = false;
                } else {
                    isDelete = true;
                }
            }
        } else {
            isDelete = true;
        }
        return isDelete;
    }

你可能感兴趣的:(java,文件过滤)