Using the Java Apache Commons Net FTPClient, is it possible to make a listFiles call that will retrieve the contents of a directory plus all its sub directories as well?
Asked
Active
Viewed 455 times
1
Martin Prikryl
- 167,268
- 50
- 405
- 846
user2868835
- 829
- 1
- 16
- 27
1 Answers
1
The library cannot do it on its own. But you can implement it using a simple recursion:
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);
}
}
}
}
Not only that the Apache Commons Net library cannot do this in one call. There's actually no API in FTP for that. Though some FTP servers have proprietary non-standard ways. For example ProFTPD has -R switch to LIST command (and its companions).
FTPFile[] remoteFiles = ftpClient.listFiles("-R " + remotePath);
See also a related C# question:
Getting all FTP directory/file listings recursively in one call
You can also consider running du -sh * . via SSH from Java.
Martin Prikryl
- 167,268
- 50
- 405
- 846