Java FTPClient 判断文件是否存在 | 代码示例
在 FTPClient 中,可以使用 'existFile(String filePath)' 方法来判断文件是否存在。这个方法会发送 FTP 命令来检查指定路径的文件是否存在。
以下是一个使用 'existFile()' 方法判断文件是否存在的示例代码:
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpClientExample {
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";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
boolean fileExists = existFile(ftpClient, filePath);
if (fileExists) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
ftpClient.logout();
ftpClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean existFile(FTPClient ftpClient, String filePath) throws Exception {
FTPFile[] files = ftpClient.listFiles(filePath);
return files.length > 0;
}
}
在上面的示例中,我们首先创建一个 'FTPClient' 实例,然后使用 'connect()' 方法连接到 FTP 服务器,再使用 'login()' 方法登录 FTP 服务器。
接下来,我们调用 'existFile()' 方法来判断文件是否存在。这个方法使用 'listFiles(String pathname)' 方法来列出指定路径下的文件,然后根据返回的文件列表来判断文件是否存在。
最后,我们使用 'logout()' 方法登出 FTP 服务器,并使用 'disconnect()' 方法断开与 FTP 服务器的连接。
注意:上面的示例代码使用了 Apache Commons Net 库来进行 FTP 操作,你需要在项目中引入这个库才能运行这个示例。
原文地址: https://www.cveoy.top/t/topic/qeOh 著作权归作者所有。请勿转载和采集!