【问题标题】:Checking file existence on FTP server检查 FTP 服务器上的文件是否存在
【发布时间】:2012-05-15 23:14:08
【问题描述】:

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

【问题讨论】:

    标签: java ftp apache-commons-net


    【解决方案1】:

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

    【讨论】:

    • 感谢您的快速回答,我检查了 FTPFile[] 数组长度以了解文件是否存在。
    【解决方案2】:

    正如公认的答案所示,在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 节中关于LIST 命令的部分中的RFC 959 说:

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

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

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


    如果服务器支持的话,更高效的是使用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 命令不使用单独的连接(与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");
    }
    

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

    【讨论】:

      【解决方案3】:

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

      代码不起作用:

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

      相反,这对我有用:

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

      【讨论】:

      • 这只是您的特定 FTP 服务器的特性。对于大多数服务器来说,这两个代码 sn-ps 之间没有区别。
      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多