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

如何检查FTP服务器中指定文件是否存在?

检测FTP服务器文件是否存在的实现方案

我看你已经在使用Apache Commons Net的FTPClient来处理FTP操作了,刚好可以基于这个库来实现文件存在性检测。下面是完整的可运行代码,以及关键步骤的说明:

完整实现代码(Groovy版本)

@Grab(group='commons-net', module='commons-net', version='3.9.0')
import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPFile

def checkFileExistsOnFtp(String server, int port, String user, String password, String filePath) {
    FTPClient ftpClient = new FTPClient()
    try {
        // 连接FTP服务器
        ftpClient.connect(server, port)
        // 登录验证
        boolean loginSuccess = ftpClient.login(user, password)
        if (!loginSuccess) {
            println("FTP登录失败")
            return false
        }

        // 开启被动模式(多数FTP服务器要求此设置以建立数据连接)
        ftpClient.enterLocalPassiveMode()

        // 核心检测逻辑:mlistFile返回null则表示文件不存在
        FTPFile ftpFile = ftpClient.mlistFile(filePath)
        return ftpFile != null && ftpFile.isFile()

    } catch (IOException e) {
        println("FTP操作出错: ${e.message}")
        e.printStackTrace()
        return false
    } finally {
        // 确保资源释放,避免连接泄漏
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout()
                ftpClient.disconnect()
            }
        } catch (IOException e) {
            e.printStackTrace()
        }
    }
}

// 调用示例,替换为你的FTP信息和目标文件路径
String ftpServer = "your-ftp-server.com"
int ftpPort = 21
String ftpUser = "your-username"
String ftpPassword = "your-password"
String targetFile = "/path/to/your/target-file.txt"

if (checkFileExistsOnFtp(ftpServer, ftpPort, ftpUser, ftpPassword, targetFile)) {
    println("File exist")
} else {
    println("File not found")
}

关键细节说明

  • 依赖处理:Groovy中用@Grab注解自动拉取Apache Commons Net依赖,Java项目则需要在pom.xml或build.gradle中手动添加对应依赖配置。
  • 被动模式:enterLocalPassiveMode()是关键配置,大部分公共FTP服务器要求使用被动模式来完成文件列表等数据交互,不设置可能导致操作失败。
  • 精准检测:mlistFile(filePath)直接定位目标路径,返回的FTPFile对象不仅能判断存在性,还能通过isFile()排除目录(如果你的需求是检测文件而非目录的话)。
  • 兼容旧服务器:如果遇到不支持mlistFile的老旧FTP服务器,可以用遍历目录的替代方案:
    // 遍历目录的替代检测逻辑
    String parentDir = "/path/to/parent"
    String fileName = "target-file.txt"
    ftpClient.changeWorkingDirectory(parentDir)
    FTPFile[] files = ftpClient.listFiles()
    boolean exists = files.any { it.isFile() && it.getName() == fileName }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:19:05