FTPClient 类没有直接提供判断文件是否存在的方法,但可以通过以下步骤来判断文件是否存在:

  1. 使用listFiles方法获取 FTP 服务器上的文件列表。
  2. 遍历文件列表,比较文件名与目标文件名是否匹配。
  3. 如果匹配,则文件存在;否则,文件不存在。

下面是一个示例代码:

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class FTPFileExistsExample {
    public static void main(String[] args) {
        String server = "ftp.example.com";
        int port = 21;
        String username = "username";
        String password = "password";
        String filePath = "/path/to/file.txt";

        try {
            FTPClient ftpClient = new FTPClient();
            ftpClient.connect(server, port);
            ftpClient.login(username, password);

            FTPFile[] files = ftpClient.listFiles();
            boolean fileExists = false;

            for (FTPFile file : files) {
                if (file.getName().equals(filePath)) {
                    fileExists = true;
                    break;
                }
            }

            if (fileExists) {
                System.out.println("File exists");
            } else {
                System.out.println("File does not exist");
            }

            ftpClient.logout();
            ftpClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请注意,上述示例使用了 Apache Commons Net 库中的 FTPClient 类。确保已将该库添加到项目的 classpath 中。

Java FTPClient 判断文件是否存在 - 完整代码示例

原文地址: https://www.cveoy.top/t/topic/qeOA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录