You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java FTP下载代码中添加正则表达式筛选特定文件

给FTP批量下载代码添加正则筛选功能

要实现按正则表达式筛选并仅下载特定文件,你可以通过以下步骤修改现有代码:

  1. 新增正则匹配参数:给方法添加预编译的正则Pattern参数(递归场景下更高效)
  2. 添加文件名匹配判断:在处理普通文件时,检查文件名是否符合正则规则,符合才执行下载
  3. 保留目录递归遍历:目录仍正常递归,确保能检索子目录中的目标文件

修改后的完整代码

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Pattern;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

private static void downloadFolder(
    FTPClient ftpClient, String remotePath, String localPath, Pattern fileNamePattern) throws IOException
{
    System.out.println("正在下载目录 " + remotePath + " 到 " + localPath);

    FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);

    for (FTPFile remoteFile : remoteFiles)
    {
        String fileName = remoteFile.getName();
        if (!fileName.equals(".") && !fileName.equals(".."))
        {
            String remoteFilePath = remotePath + "/" + fileName;
            String localFilePath = localPath + "/" + fileName;

            if (remoteFile.isDirectory())
            {
                new File(localFilePath).mkdirs();
                // 递归遍历子目录,继续应用正则筛选
                downloadFolder(ftpClient, remoteFilePath, localFilePath, fileNamePattern);
            }
            else
            {
                // 检查文件名是否匹配正则规则
                if (fileNamePattern.matcher(fileName).matches())
                {
                    System.out.println("正在下载文件 " + remoteFilePath + " 到 " + localFilePath);

                    // 使用try-with-resources自动关闭流,避免资源泄漏
                    try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFilePath)))
                    {
                        if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
                        {
                            System.out.println("下载文件失败:" + remoteFilePath);
                        }
                    }
                }
                else
                {
                    System.out.println("跳过不符合规则的文件:" + fileName);
                }
            }
        }
    }
}

关键修改说明

  • 正则参数传递:调用时通过Pattern.compile("你的正则表达式")传入规则,比如要下载所有.txt文件,就用Pattern.compile(".*\\.txt$")
  • 匹配判断逻辑:通过fileNamePattern.matcher(fileName).matches()验证文件名,只有符合规则的文件才会触发下载
  • 流资源优化:改用try-with-resources语法自动关闭输出流,避免手动关闭可能出现的资源泄漏问题

调用示例

// 示例:下载所有以.pdf结尾的文件
Pattern pdfPattern = Pattern.compile(".*\\.pdf$");
downloadFolder(ftpClient, "/remote/ftp/docs", "/local/save/docs", pdfPattern);

内容的提问来源于stack exchange,提问作者TheUnborn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:43:21