使用Java Apache Commons Net库检索所有子文件夹的内容

时间:2019-03-11 06:15:01

标签: java ftp ftp-client apache-commons-net

使用Java Apache Commons Net FTPClient,是否可以进行listFiles调用来检索目录及其所有子目录的内容?

1 个答案:

答案 0 :(得分:0)

库无法自行执行。但是您可以使用简单的递归来实现它:

private static void listFolder(FTPClient ftpClient, String remotePath) throws IOException
{
    System.out.println("Listing folder " + remotePath);
    FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
    for (FTPFile remoteFile : remoteFiles)
    {
        if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
        {
            String remoteFilePath = remotePath + "/" + remoteFile.getName();

            if (remoteFile.isDirectory())
            {
                listFolder(ftpClient, remoteFilePath);
            }
            else
            {
                System.out.println("Found file " + remoteFilePath);
            }
        }
    }
}

不仅Apache Commons Net库无法一次调用。 FTP中实际上没有用于此的API。尽管某些FTP服务器具有专有的非标准方式。例如,ProFTPD具有-R切换到LIST命令(及其伴随命令)。

FTPFile[] remoteFiles = ftpClient.listFiles("-R " + remotePath);

另请参阅相关的C#问题:
Getting all FTP directory/file listings recursively in one call

相关问题