Checking file existence on FTP server

时光毁灭记忆、已成空白 提交于 2019-11-26 14:24:40

问题


Is there an efficient way to check the existence of a file on a FTP server? I'm using Apache Commons Net. I know that I can use the listNames method of FTPClient to get all the files in a specific directory and then I can go over this list to check if a given file exists, but I don't think it's efficient especially when the server contains a lot of files.


回答1:


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




回答2:


Using a full path to a file in listFiles (or mlistDir) call, as the accepted answer shows, should indeed 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");
}

The RFC 959 in the section 4.1.3 in the part about the LIST command says:

If the pathname specifies a file then the server should send current information on the file.

Though if you are going to check for many files, this will be rather ineffective. A use of the LIST command actually involves several commands, waiting for their responses, and mainly, opening a data connection. Opening a new TCP/IP connection is a costly operation, even more so, when an encryption is used (what is a must these days).

Also LIST command is even more ineffective for testing an existence of a folder, as it results in a transfer of a complete folder contents.


More efficient is to use mlistFile (MLST command), if the server supports it:

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 test an existence of a directory.

MLST command does not use a separate connection (contrary to LIST).


If the server does not support 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 test an existence of a directory.




回答3:


The accepted answer did not work for me.

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");


来源:https://stackoverflow.com/questions/10482204/checking-file-existence-on-ftp-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!