检查FTP服务器上是否存在文件

有没有一种有效的方法来检查FTP服务器上是否存在文件? 我正在使用Apache Commons Net。 我知道我可以使用FTPClientlistNames方法来获取特定目录中的所有文件,然后我可以查看这个列表以检查给定文件是否存在,但我不认为它是有效的,尤其是当服务器包含很多文件。

listFiles(String pathName)应该适用于单个文件。

正如接受的答案所示,使用mlistDir (或mlistDir )调用中文件的完整路径确实适用于许多 FTP服务器:

 String remotePath = "/remote/path/file.txt"; FTPFile[] remoteFiles = ftpClient.listFiles(remotePath ); if (remoteFiles.length > 0) { System.out.println("File " + remoteFiles[0].getName() + " exists"); } else { System.out.println("File " + remotePath + " does not exists"); } 

但它实际上违反了FTP规范,因为它映射到FTP命令

 LIST /remote/path/file.txt 

根据规范,FTP LIST命令仅接受文件夹的路径。

实际上, 大多数FTP服务器都可以在LIST命令中接受文件掩码 (确切的文件名也是一种掩码)。 但这是标准的,并非所有FTP服务器都支持它(理所当然)。


适用于任何FTP服务器的可移植代码必须在本地过滤文件:

 FTPFile[] remoteFiles = ftpClient.listFiles("/remote/path"); Optional remoteFile = Arrays.stream(remoteFiles).filter( (FTPFile remoteFile2) -> remoteFile2.getName().equals("file.txt")).findFirst(); if (remoteFile.isPresent()) { System.out.println("File " + remoteFile.get().getName() + " exists"); } else { System.out.println("File does not exists"); } 

更高效的是使用mlistFileMLST命令),如果服务器支持它:

 String remotePath = "/remote/path/file.txt"; FTPFile remoteFile = ftpClient.mlistFile(remotePath); if (remoteFile != null) { System.out.println("File " + remoteFile.getName() + " exists"); } else { System.out.println("File " + remotePath + " does not exists"); } 

此方法用于测试目录的存在。


如果服务器不支持MLST命令,则可以滥用 getModificationTimeMDTM命令):

 String timestamp = ftpClient.getModificationTime(remotePath); if (timestamp != null) { System.out.println("File " + remotePath + " exists"); } else { System.out.println("File " + remotePath + " does not exists"); } 

此方法不能用于测试目录的退出。