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 =
开发者_如何学JAVA "There are currently " + totalDIRS + " directories within the ROOT directory";
client.disconnect(true);
} catch (Exception e) {
System.out.println(e.toString());
}
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
.
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...
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);
}
}
}
}
精彩评论