21

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

4

3 回答 3

27

listFiles(String pathName)对于单个文件应该可以正常工作。

于 2012-05-07T12:54:02.423 回答
14

listFiles正如接受的答案所示,在(或)调用中使用文件的完整路径mlistDir确实应该有效:

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

关于命令部分的 4.1.3 节中的RFC 959LIST说:

如果路径名指定了一个文件,那么服务器应该发送该文件的当前信息。

虽然如果您要检查许多文件,这将是相当无效的。命令的使用LIST实际上涉及到几个命令,等待它们的响应,主要是打开一个数据连接。打开一个新的 TCP/IP 连接是一项代价高昂的操作,在使用加密时更是如此(现在必须这样做)。

此外LIST,命令对于测试文件夹的存在甚至更加无效,因为它会导致传输完整的文件夹内容。


更有效的是使用mlistFile( MLSTcommand),如果服务器支持的话:

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命令不使用单独的连接(与 相反LIST)。


如果服务器不支持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");
}

此方法不能用于测试目录是否存在。

于 2018-04-17T11:46:07.603 回答
2

接受的答案对我不起作用。

代码不起作用:

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

相反,这对我有用:

ftpClient.changeWorkingDirectory("/remote/path");
FTPFile[] remoteFiles = ftpClient.listFiles("file.txt");
于 2019-07-05T12:18:30.420 回答