在Java中判断FTP文件是否存在
在Java中判断FTP服务器上的文件是否存在,可以使用Apache Commons Net库中的FTPClient类,以下是几种实现方法:

使用FTPClient.listFiles()
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public boolean isFileExists(String server, int port, String username, String password, String remoteFilePath) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
FTPFile[] files = ftpClient.listFiles(remoteFilePath);
return files != null && files.length > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用FTPClient.listFiles()并检查文件名
public boolean isFileExists(String server, int port, String username, String password, String remoteFilePath) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
String fileName = new File(remoteFilePath).getName();
FTPFile[] files = ftpClient.listFiles(new File(remoteFilePath).getParent());
for (FTPFile file : files) {
if (file.getName().equals(fileName)) {
return true;
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用FTPClient.sendNoOp()检查连接后检查文件
public boolean isFileExists(String server, int port, String username, String password, String remoteFilePath) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
// 检查连接是否仍然有效
if (!ftpClient.sendNoOp()) {
return false;
}
// 切换到文件所在目录
String parentPath = new File(remoteFilePath).getParent();
if (parentPath != null && !parentPath.isEmpty()) {
ftpClient.changeWorkingDirectory(parentPath);
}
// 检查文件是否存在
String fileName = new File(remoteFilePath).getName();
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
if (file.getName().equals(fileName)) {
return true;
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
-
确保已添加Apache Commons Net依赖:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.9.0</version> </dependency> -
对于大文件或大量文件,
listFiles()方法可能会消耗较多资源,此时可以考虑使用FTPClient.listFiles()并限制返回的文件数量。 -
如果文件名包含特殊字符或路径中包含空格,可能需要进行适当的编码或转义。
-
考虑添加超时设置:
(图片来源网络,侵删)ftpClient.setDefaultTimeout(10000); // 10秒超时 ftpClient.setConnectTimeout(10000); ftpClient.setDataTimeout(10000);
-
如果使用被动模式(PASV),可以设置:
ftpClient.enterLocalPassiveMode();
方法都可以有效地判断FTP服务器上的文件是否存在,选择哪种方法取决于你的具体需求和FTP服务器的配置。

