Checking the existence of a file on an FTP server

Is there an effective way to check for a file on an FTP server? I am using Apache Commons Net. I know that I can use the listNames FTPClient method to get all the files in a specific directory, and then I can look at this list to check if this file exists, but I do not consider it effective, especially when the server contains a lot of files.

+15
java ftp apache-commons-net
source share
3 answers

listFiles(String pathName) should work fine for a single file.

+21
source share

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.

+10
source share

The accepted answer did not work for me.

The code did not work:

 String remotePath = "/remote/path/file.txt"; FTPFile[] remoteFiles = ftpClient.listFiles(remotePath); 

Instead, this works for me:

 ftpClient.changeWorkingDirectory("/remote/path"); FTPFile[] remoteFiles = ftpClient.listFiles("file.txt"); 
0
source share

All Articles