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 717 times
1

Martin Prikryl
- 188,800
- 56
- 490
- 992

user2868835
- 1,250
- 3
- 19
- 33
1 Answers
2
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
- 188,800
- 56
- 490
- 992