Recursively list files and directories in an FTP server using Java

你离开我真会死。 提交于 2021-02-08 08:35:39

问题


I'm currently using a Java FTP library (ftp4j) to access a FTP server. I want to do a file count and directory count for the server, but this means I would need to list files within directories within directories within directories, etc.

How is this achievable? Any hints would be greatly appreciated.

Extract from the code:

client = new FTPClient();
try {
    client.connect("");
    client.login("", "");
    client.changeDirectory("/");
    FTPFile[] list = client.list();
    int totalDIRS = 0;
    int totalFILES = 0;
    for (FTPFile ftpFile : list) {
        if (ftpFile.getType() == FTPFile.TYPE_DIRECTORY) {
            totalDIRS++;
        }
    }
    message =
        "There are currently " + totalDIRS + " directories within the ROOT directory";
    client.disconnect(true);
} catch (Exception e) {
    System.out.println(e.toString());
}

回答1:


Make a recursive function that given a file that might be a directory returns the number of files and directories in it. Use isDir and listFiles.




回答2:


Try using recursive functions. This is could be a function that checks a directory for files, then you can do a check if a file has a child, that would be a directory. If it has a child you can call that same function again for that directory, etc.

Like this pseudo java here:

void Function(String directory){
 ... run through files here
 if (file.hasChild())
 {
  Function(file.getString());
 }
}

I'm sure you can use that kind of coding in counting the files as well...




回答3:


Just use a recursive function like below.

Note that my code uses Apache Commons Net, not ftp4j, what the question is about. But the API is pretty much the same and ftp4j seems to be an abandoned project now anyway.

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("Foud remote file " + remoteFilePath);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/6267890/recursively-list-files-and-directories-in-an-ftp-server-using-java

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