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

问题描述 投票:0回答:1

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

java ftp ftp-client apache-commons-net
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.