Using the full file path in listFiles (or mlistDir ), as the accepted answer shows, should really work:
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"); }
RFC 959 in section 4.1.3 on the LIST command reads:
If the path indicates a file, then the server should send the current information about the file.
Although, if you are going to check a lot of files, it will be quite inefficient. Using the LIST command actually includes several commands that are waiting for their responses and mainly open the data connection. Opening a new TCP / IP connection is an expensive operation, even more so when encryption is used (which is mandatory these days).
In addition, the LIST command is even more ineffective for checking the existence of a folder, since it causes the transfer of the full contents of the folder.
It is more efficient to use mlistFile ( MLST command) if the server supports this:
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"); }
This method can be used to verify the existence of a directory.
The MLST command does not use a separate connection (unlike LIST ).
If the server does not support the MLST command, you can abuse getModificationTime ( MDTM command):
String timestamp = ftpClient.getModificationTime(remotePath); if (timestamp != null) { System.out.println("File " + remotePath + " exists"); } else { System.out.println("File " + remotePath + " does not exists"); }
This method cannot be used to verify the existence of a directory.
Martin Prikryl
source share