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

递归读取指定目录下的文件

序言

需要读取sftp服务器上符合指定的文件名正则的文件列表,目前想到的最好的办法就是递归。

我这里引入的依赖是:

        <!--   jsch-sftp连接     --><dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency>

不废话直接上代码:

  public static List<String> getFileList(ChannelSftp channelSftp, String path, String fileNamePattern, Integer filePathDepth) {List<String> fileList = Lists.newLinkedList();try {Pattern pattern = Pattern.compile(fileNamePattern);Vector<ChannelSftp.LsEntry> files = channelSftp.ls(path);//读取的根路径下一级就是文件if (1 == filePathDepth) {for (ChannelSftp.LsEntry entry : files) {String fileName = entry.getFilename();//找到和规则(文件名正则)匹配的文件if (pattern.matcher(fileName).matches()) {//拼接全路径String fullPath = path + fileName;fileList.add(fullPath);}}} else {//从读取根路径下开始算目录深度时,目录深度大于1就使用递归来读取文件列表manyDirFileList(channelSftp, path, fileNamePattern, fileList, bComFilesaveReadruleDO.getDirPattern());}} catch (Exception e) {log.error("获取sftp指定目录下的文件列表失败,{}", e.getMessage());}return fileList;}/*** 递归获取提供的路径下多级目录下符合正则的所有文件** @param channelSftp ftp对象* @param path        路径* @param fileList    文件列表**/public static void manyDirFileList(ChannelSftp channelSftp, String path, String fileNamePattern,List<String> fileList, String dirPattern) throws Exception {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 l : vector) {ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) l;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() ? "/" : "");manyDirFileList(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());throw new Exception("递归获取SFTP指定目录下的文件列表失败,路径:" + path + ",异常信息:" + e.getMessage());}}

另外还有一个需求就是只读取10个文件:

 public static List<String> getFileListFor10(ChannelSftp channelSftp,  String path, String fileNamePattern, Integer filePathDepth) {List<String> fileList = Lists.newLinkedList();try {Pattern pattern = Pattern.compile(fileNamePattern);Vector<ChannelSftp.LsEntry> files = channelSftp.ls(path);//读取的根路径下一级就是文件if (1 == filePathDepth) {for (ChannelSftp.LsEntry entry : files) {if (fileList.size() > 10) {log.info("已读取10个文件,不再读取目录:{}下的文件", path);break;}String fileName = entry.getFilename();//找到和规则(文件名正则)匹配的文件if (pattern.matcher(fileName).matches()) {//拼接全路径String fullPath = path + fileName;fileList.add(fullPath);}}} else {//从输入的根路径下开始算目录深度时,目录深度大于1就使用递归来读取文件列表manyDirFileListFor10(channelSftp, path, fileNamePattern, fileList, bComFilesaveReadruleDO.getDirPattern());}} catch (Exception e) {log.error("获取sftp指定目录下的文件列表失败,{}", e.getMessage());}return fileList;}/*** 递归获取提供的路径下多级目录下符合正则的前10个文件** @param channelSftp ftp对象* @param path        路径* @param fileList    文件列表**/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());}}

-----------------知道的越多, 不知道的越多--------------------

http://www.lryc.cn/news/506248.html

相关文章:

  • 【模型压缩】原理及实例
  • 常用的JVM启动参数有哪些?
  • Curvelet 变换与FDCT
  • Django Admin 管理工具
  • Android笔记【19】
  • 矩阵在资产收益(Asset Returns)中的应用:以资产回报矩阵为例(中英双语)
  • Docker 中如何限制CPU和内存的使用 ?
  • 【AIGC-ChatGPT进阶提示词-《动图生成》】怪物工厂:融合想象力与创造力的奇幻世界
  • docker 使用 xz save 镜像
  • C#经典算法面试题
  • vulnhub靶场【DriftingBlues】之9 final
  • 有124个叶子节点的,完全二叉树最多有多少个节点
  • 从RNN到Transformer:生成式AI自回归模型的全面剖析
  • Java爬虫大冒险:如何征服1688商品搜索之巅
  • 基于Spring Boot的无可购物网站系统
  • 智能人家谱程序创意
  • Redis 7.x哨兵模式如何实现?基于Spring Boot 3.x版
  • 解决QTCreator在Debug时无法显示std::string类型的问题
  • leetcode 面试经典 150 题:无重复字符的最长子串
  • 0101多级nginx代理websocket配置-nginx-web服务器
  • 【前端】Jquery拍照,通过PHP将base64编码数据转换成PNG格式,并保存图像到本地
  • websocket再项目中的使用
  • ajax同步执行async:false无效的解决方法
  • 基于Qt的登陆界面设计
  • HarmonyOS 输入框组件:TextInput 和 TextArea 深度解析
  • 【Golang】 Go 语言中的 Struct、JSON 和 Map 互转:详细指南
  • Azure Function流式返回
  • 智能座舱进阶-应用框架层-Jetpack主要组件
  • GitLab分支管理策略和最佳实践
  • 【Unity】【VR开发】实现VR屏幕共享应用的几个重要插件和参考资料分享