当前位置: 首页 > article >正文

java 递归读取前10个匹配的文件所在的全路径

需求

有个需求:在连接ftp成功后,读取指定目录下匹配正则表达式的前10个文件。很显然这个需要使用递归,因为会有不同层级的文件目录,不能写死来处理。

第一版代码展示

public static void test(ChannelSftp channelSftp, 			String path, String fileNamePattern,List<String> fileList, String dirPattern) {
   // 如果已经找到了10个文件,直接返回,不再递归
   if (fileList.size() >= 10) {
       log.info("已读取10个文件,不再读取目录:{}下的文件", path);
       return;
   }
   try {
       List<Pattern> dirPatterns = new ArrayList<>();
       if (StringUtils.isNotEmpty(dirPattern)) {
           for (String pat : dirPattern.split(",")) {
               dirPatterns.add(Pattern.compile(pat.trim()));
           }
       }
       Pattern fileNamePat = Pattern.compile(fileNamePattern);

       if (isDirectory(channelSftp, path)) {
           Vector<?> vector = channelSftp.ls(path);
           for (Object o : vector) {
               ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) o;
               String fileName = file.getFilename();
               boolean isDirMatch = dirPatterns.isEmpty();
               for (Pattern dirPat : dirPatterns) {
                   if (dirPat.matcher(fileName).matches()) {
                       isDirMatch = true;
                       break;
                   }
               }
               if (fileName.equals(".") || fileName.equals("..")) {
                   continue;
               }
               if (isDirMatch || fileNamePat.matcher(fileName).matches()) {
                   String fullPath = path + fileName + (file.getAttrs().isDir() ? "/" : "");
                   manyDirFileListFor10(channelSftp, fullPath, fileNamePattern, fileList, dirPattern);
               }
           }
       } else {
           String fileName = path.substring(path.lastIndexOf("/") + 1);
           if (fileNamePat.matcher(fileName).matches()) {
               fileList.add(path);
           }
       }
   } catch (SftpException e) {
       log.error("获取FTP指定目录下的文件异常,路径:{},异常信息:{}", path, e.getMessage());
   } catch (Exception e) {
       log.error("递归获取SFTP指定目录下的文件列表失败,路径:{},异常信息:{}", path, e.getMessage());
   }
}

当fileList有10个元素了之后,走到return之后并没有结束,而是会继续往下走递归,于是有了第二版:

public static void manyDirFileListFor10(ChannelSftp channelSftp, String path, String fileNamePattern,
                                       List<String> fileList, String dirPattern) {
        try {
            List<Pattern> dirPatterns = new ArrayList<>();
            if (StringUtils.isNotEmpty(dirPattern)) {
                for (String pat : dirPattern.split(",")) {
                    dirPatterns.add(Pattern.compile(pat.trim()));
                }
            }
            Pattern fileNamePat = Pattern.compile(fileNamePattern);

            if (isDirectory(channelSftp, path)) {
                Vector<?> vector = channelSftp.ls(path);
                for (Object o : vector) {
                    // 如果已经找到了10个文件,直接返回,不再递归
                    if (fileList.size() >= 10) {
                        log.info("已读取10个文件,不再读取目录:{}下的文件", path);
                        break;
                    }
                    ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) o;
                    String fileName = file.getFilename();
                    boolean isDirMatch = dirPatterns.isEmpty();
                    for (Pattern dirPat : dirPatterns) {
                        if (dirPat.matcher(fileName).matches()) {
                            isDirMatch = true;
                            break;
                        }
                    }
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    if (isDirMatch || fileNamePat.matcher(fileName).matches()) {
                        String fullPath = path + fileName + (file.getAttrs().isDir() ? "/" : "");
                        manyDirFileListFor10(channelSftp, fullPath, fileNamePattern, fileList, dirPattern);
                    }
                }
            } else {
                String fileName = path.substring(path.lastIndexOf("/") + 1);
                if (fileNamePat.matcher(fileName).matches()) {
                    fileList.add(path);
                }
            }
        } catch (SftpException e) {
            log.error("获取FTP指定目录下的文件异常,路径:{},异常信息:{}", path, e.getMessage());
        } catch (Exception e) {
            log.error("递归获取SFTP指定目录下的文件列表失败,路径:{},异常信息:{}", path, e.getMessage());
        }
    }

这里将fileList.size()>=10的判断放在for循环里,这样就可以了。
----------------------------知道的越多,不知道的越多-------------------------


http://www.kler.cn/news/310070.html

相关文章:

  • 松散绑定是什么?
  • 切换淘宝最新镜像源:优化NPM包管理的极致体验
  • windows C++ 并行编程-异步消息块(一)
  • 【系统架构设计师-2016年真题】案例分析-答案及详解
  • Java从入门到精通学习框架(三)
  • Mybatis+Druid+MybatisPlus多数据源配置
  • 闲鱼网页版开放,爬虫的难度指数级降低。
  • LDD学习启程(TODO)
  • 【React】React18新特性 - startTransition
  • vue-ts-demo
  • 【C-项目】网盘(一期,无限进程版)
  • 什么是数据治理?如何保障数据质量安全
  • 大舍传媒:尼日利亚传统新闻媒体宣传助力新兴行业蓬勃发展
  • 百收SEO蜘蛛池
  • Spring Boot 项目的 pom.xml 中,groupId、artifactId 等信息要如何定义?——定义规则及案例
  • 渗透测试综合靶场 DC-1 通关详解
  • (PySpark)RDD实验实战——求商品销量排行
  • 教师薪酬管理系统的设计与实现
  • Springboot与minio:
  • 《C++魔法:零开销实现抽象工厂模式》
  • LeetCode 滑动窗口 滑动子数组的美丽值
  • Java迭代器Iterator和Iterable有什么区别?
  • 2024 ccpc 网络赛题解
  • SEO之页面优化(一-页面标题2)
  • Java操作数栈分析
  • 【JAVA基础】实现Tomcat基本功能
  • PyQt5-QCheckBox-开关按钮
  • Maven详细介绍
  • 【postgres】笔记
  • 重修设计模式-结构型-适配器模式