java如何判断ftp中某个文件是否存在
时间: 2024-02-09 12:10:34 浏览: 31
在Java中,可以使用Apache Commons Net库中的FTPClient类来操作FTP服务器,判断FTP服务器上是否存在某个文件可以使用其listFiles()方法。具体操作步骤如下:
1. 连接FTP服务器
```
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, password);
```
2. 判断文件是否存在
```
FTPFile[] files = ftpClient.listFiles(remotePath + "/" + fileName);
if (files.length > 0) {
// 文件存在
} else {
// 文件不存在
}
```
其中,remotePath为FTP服务器上的路径,fileName为要判断的文件名。如果该文件存在,listFiles()方法会返回一个长度大于0的FTPFile数组,否则返回长度为0的数组。
3. 关闭连接
```
ftpClient.logout();
ftpClient.disconnect();
```
完整代码示例:
```
public static boolean isFileExistOnFtpServer(String server, int port, String user, String password, String remotePath, String fileName) throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, password);
FTPFile[] files = ftpClient.listFiles(remotePath + "/" + fileName);
ftpClient.logout();
ftpClient.disconnect();
return files.length > 0;
}
```