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

序言

需要读取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.mzph.cn/pingmian/64863.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

<代码随想录> 算法训练营-2024.12.21

今日专题 &#xff1a;动态规划、打家劫舍 总结&#xff1a; 198. 打家劫舍 class Solution:def rob(self, nums: List[int]) -> int:#dp[n]max(dp[n-1],dp[n-2]nums[n])sizelen(nums)if size1:return nums[0]#n的状态只依赖n-1和n-2的状态&#xff0c;对状态进行压缩i,j…

uniapp 将base64字符串保存为图片、Word、Excel、音频、视频等文件

function blobToBase64(blob) {return new Promise((resolve, reject) > {const reader new FileReader();reader.onerror reject;reader.onload () > {if (typeof reader.result string) {// 去掉"data:..."前缀&#xff0c;只保留 Base64 部分resolve(re…

[计算机网络]唐僧的”通关文牒“NAT地址转换

1.NAT&#xff1a;唐僧的通关文牒 在古老的西游记中&#xff0c;唐僧师徒四人历经九九八十一难&#xff0c;终于取得了真经。然而&#xff0c;他们并不是一开始就获得了通关文牒&#xff0c;而是经过了重重考验&#xff0c;最终得到了国王的认可&#xff0c;才顺利通过了各个关…

音视频学习(二十四):hls协议

基本原理 HLS协议通过将视频文件切分成多个小的媒体段&#xff08;通常是10秒左右的.ts文件&#xff09;&#xff0c;并通过HTTP传输给客户端。视频播放过程中&#xff0c;客户端按顺序请求这些小段文件来逐步播放整个视频流。HLS还支持多种码率&#xff0c;以便适应不同网络条…

tcp_ack函数

tcp_ack 是 TCP/IP 协议栈中的一个函数,用于处理传入的数据包的确认(ACK)。这个函数在 Linux 内核的 TCP 实现中被用来确保可靠的数据传输。 具体来说,TCP(传输控制协议)是一种面向连接的协议,确保数据在网络中的可靠传输。ACK(确认)是 TCP 连接的一个基本元素,当一方…

WPF实现曲线数据展示【案例:震动数据分析】

wpf实现曲线数据展示&#xff0c;函数曲线展示&#xff0c;实例&#xff1a;震动数据分析为例。 如上图所示&#xff0c;如果你想实现上图中的效果&#xff0c;请详细参考我的内容&#xff0c;创作不易&#xff0c;给个赞吧。 一共有两种方式来实现&#xff0c;一种是使用第三…

【CVE-2024-56145】PHP 漏洞导致 Craft CMS 出现 RCE

大多数开发人员都同意,与 15 年前相比,PHP 是一种更加理智、更加安全和可靠的语言。PHP5早期的不良设计已让位于更好的开发生态系统,其中包括类、自动加载、更严格的类型、更理智的语法以及一大堆其他改进。安全性也没有被忽视。 register_globals一些老读者可能还记得和的…

7 家使用量子计算的公司

劳斯莱斯、Deloitte、BASF、Roche、富士通、JPMorgan和宝马是率先开展量子计算实验的部分公司。 商用量子计算的实现仍需数年时间&#xff0c;但这并未阻止世界上一些知名企业对其进行试验。在许多情况下&#xff0c;利用当下有噪声的中等规模量子&#xff08;NISQ&#xff09…

最大似然检测在通信解调中的应用

最大似然检测&#xff08;Maximum Likelihood Detection&#xff0c;MLD&#xff09;&#xff0c;也称为最大似然序列估计&#xff08;Maximum Likelihood Sequence Estimation&#xff0c;MLSE&#xff09;&#xff0c;是一种在通信系统中广泛应用的解调方法。其核心思想是在给…

JAVA服务器端发送邮件问题 Could not connect to SMTP host

写在前面 在开发过程中&#xff0c;发送邮件经过本地测试是没有问题&#xff0c;部署到服务器上后&#xff0c;发送邮件一直报 Could not connect to SMTP host : smtp.yeah.net, port: 465 解决方法 网上各种解决方案&#xff0c;都试了一遍都未能解决这个报错问题&#xf…

完整微服务设计 功能实现

我们将以一个简单的电商系统为例&#xff0c;实现微服务架构&#xff0c;逐步用Java代码详细实现每个模块&#xff0c;并配合注释帮助小白理解。在这个实现中&#xff0c;我们使用以下工具和框架&#xff1a; Spring Boot&#xff1a;用于构建微服务。Spring Cloud&#xff1a…

Android -- 双屏异显之方法二

Android – 双屏异显之方法二: DisplayManager PS: 1. 使用改方法主板需连接至少两个输出显示屏&#xff1b; 2. 副屏内部实现与MediaRouter下一样&#xff1b;使用方法 # 主屏activity内&#xff1a; private SecondDisplay secondDisplay;private void dualScreen3288() {D…

jvm字节码中方法的结构

“-Xss”这一名称并没有一个特定的“为什么”来解释其命名&#xff0c;它更多是JVM&#xff08;Java虚拟机&#xff09;配置参数中的一个约定俗成的标识。在JVM中&#xff0c;有多个配置参数用于调整和优化Java应用程序的性能&#xff0c;这些参数通常以一个短横线“-”开头&am…

结合大语言模型的异常检测方法研究

论文链接 Research on Anomaly Detection Methodology Combining Large Language Models 论文主要内容 研究背景与目的&#xff1a; 随着大数据和人工智能技术的发展&#xff0c;异常检测在数据分析中变得越来越重要。 本研究提出了一种名为SemantEdge Detection (SED)的新…

【服务器】MyBatis是如何在java中使用并进行分页的?

MyBatis 是一个支持普通 SQL 查询、存储过程和高级映射的持久层框架。它消除了几乎所有的 JDBC 代码和参数的手动设置以及结果集的检索。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java 的 POJO&#xff08;Plain Old Java Objects&#xff0c;普通老式 …

Phono3py hdf5文件数据读取与处理

Phono3py是一个主要用python写的声子-声子相互作用相关性质的模拟包&#xff0c;可以基于有限位移算法实现三阶力常数和晶格热导率的计算过程&#xff0c;同时输出包括声速&#xff0c;格林奈森常数&#xff0c;声子寿命和累积晶格热导率等参量。 相关介绍和安装请参考往期推荐…

centos7下docker 容器实现redis主从同步

1.下载redis 镜像 docker pull bitnami/redis2. 文件夹授权 此文件夹是 你自己映射到宿主机上的挂载目录 chmod 777 /app/rd13.创建docker网络 docker network create mynet4.运行docker 镜像 安装redis的master -e 是设置环境变量值 docker run -d -p 6379:6379 \ -v /a…

ManimCommunity 设置背景颜色

ManimCommunity 设置背景颜色 flyfish 主要是这句 self.camera.background_color WHITE 完整代码 class OpeningManim(Scene):def construct(self):self.camera.background_color WHITE title Tex(r"This is some \LaTeX")basel MathTex(r"\sum_{n1}^\in…

【数值特性库】入口文件

数值特性库入口文件为lib.rs。该文件定义一系列数字特性的trait&#xff08;特征&#xff09;&#xff0c;这些特性可以被不同的数字类型实现&#xff0c;从而提供一套通用的数值操作方法。下面是对代码中关键部分的解释&#xff1a; 一、基础设置 #![doc(html_root_url “h…

matlab绘图时设置左、右坐标轴为不同颜色

目录 一、需求描述 二、实现方法 一、需求描述 当图中存在两条曲线&#xff0c;需要对两条曲线进行分别描述时&#xff0c;应设置左、右坐标轴为不同颜色&#xff0c;并设置刻度线&#xff0c;且坐标轴颜色需要和曲线颜色相同。 二、实现方法 1.1、可以实现&#xff1a; 1…