我希望我的应用程序列出我的FTP服务器上的所有目录和文件。这是来自How to list ftp directories with android?的代码:
FTPFile[] files = null;
files = ftpClient.listDirectories();
String path = null;
for (int i = 0; i < files.length; i++) {
path = files[0].getName();
Log.d("CONNECT", "Directories: "+ files[i].getName());
}
FTPFile[] files2 = ftpClient.listFiles(topPath);
for (int j = 0; j < files2.length; j++) {
Log.d("CONNECT", "Below " + files[j].getName()
+ " is " + files2[j].getName());
}
}
现在这只适用于前两层。如何设置尽可能深入,以便列出文件夹中文件夹中的文件夹等文件?
提前致谢:)
现在我递归地尝试了(不完全):
{ ...
FTPFile[] files = ftpClient.listFiles();
listContent(files);
.... }
private void listContent(FTPFile[] file) throws IOException {
FTPFile[] list = ftpClient.listDirectories();
if (list != null) {
for (FTPFile f : list) {
if (f.isDirectory()) {
Log.d(TAG, "directory: " + f.getName());
} else {
Log.d(TAG, "file: " + f.getName());
}
}
listContent(list);
} else return;
}
这段代码让我只得到第一层目录,FTPFile []在新的循环中被覆盖。 我怎样才能做到这一点?
更新: 这是我的解决方案。此代码遍历host-adress的全部内容。感谢所有帮助过我的人:
private void listContent(String s) throws IOException {
try {
FTPFile[] ftpFiles = ftpClient.listFiles(s);
int length = ftpFiles.length;
for (int i = 0; i < length; i++) {
String name = ftpFiles[i].getName();
boolean isFile = ftpFiles[i].isFile();
if (isFile) {
Log.i(TAG, "File : " + name);
}
} else {
Log.i(TAG, "Directory : " + name);
if (ftpChangeDirectory(name) == true) {
Log.d("ftpChangeDirectory", name);
String newDir = ftpGetCurrentWorkingDirectory();
Log.d(TAG, "new Dir: " + newDir);
listContent(newDir);
}
}
}
ftpChangeDirectory("..");
String test = ftpGetCurrentWorkingDirectory();
Log.d("dirUp", test);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
我无法测试它,但这样的事情应该有效:
private void listAllFiles(String path) // path is the top folder to start the search
{
FTPFile[] files = ftpClient.listFiles(path); // Search all the files in the current directory
for (int j = 0; j < files.length; j++) {
Log.d("CONNECT", "Files: " + files[j].getName()); // Print the name of each files
}
FTPFile[] directories = ftpClient.listDirectories(path); // Search all the directories in the current directory
for (int i = 0; i < directories.length; i++) {
String dirPath = directories[i].getName();
Log.d("CONNECT", "Directories: "+ dirPath); // Print the path of a sub-directory
listAllFiles(dirPath); // Call recursively the method to display the files in the sub-directory
}
}
无论如何,我强烈建议您理解代码并检查此link以了解有关递归的更多信息。