获取所有子文件夹的列表

时间:2015-03-13 18:45:20

标签: java algorithm recursion functional-programming logic

我有一个程序逻辑问题,如何获取服务器上所有文件夹的列表:

让我们说,我有一个如下文件夹结构,我想获得其中所有文件夹的列表:

![在此处输入图片说明] [1]



String rootDirectory = “Root”; 
CmdClient client = null; 
client.connect("demo.asperasoft.com", "asperaweb", "demoaspera", 22);

// This method gives list of files inside param folder CmdReplyFile cmdfiles=client.execLs(rootDirectory);

//this method gives a list of files 
File[] fileObjects = cmdfiles.getFileList();

//this method gives file count 
int fileCount= cmdfiles.getFileCount();




此处的文件类不是Java文件类。现在,当我试图打印所有文件夹的列表时,它只是给了我:

α Beta版 伽马



private void getFolderList(String rootDirectory) throws IOException, CmdClientException {
        CmdReplyFile cmdfiles=client.execLs(rootDirectory);
        File[] fileObjects = cmdfiles.getFileList();
        for (File fileObject : fileObjects) {
            if (fileObject.isDirectory()) {
                System.out.println(fileObject.getName());
                getFolderList(fileObject.getName());
            }
        }




请提出可能的逻辑。

2 个答案:

答案 0 :(得分:1)

谢谢Kartic!我能用你的解决方案做到这一点:

public void getListOfFolders(String rootPath) throws IOException, CmdClientException {
    List<String> folders = new LinkedList<String>();
    folders.add(rootPath);
    getFolders(rootPath, folders);

    for (String items : folders){
        System.out.println("Folders: "+items.toString());
    }
}

public void getFolders(String directoryName, List<String> folders) throws IOException, CmdClientException {
    CmdReplyFile cmdfiles=client.execLs(directoryName);
    File[] fileObjects = cmdfiles.getFileList();
    String dirStructure=folders.get(folders.size()-1).toString();
    for (File file : fileObjects) {
        if (file.isDirectory()) {
            String folderPath=dirStructure+file.getName()+"/";
            folders.add(folderPath);
            getFolders(folderPath, folders);
        }
    }
}

答案 1 :(得分:0)

我希望以下代码能满足您的要求:

public void getListOfFolders(String rootPath) {
    List<String> folders = new LinkedList<String>();
    getFolders(rootPath, folders);
    // Now folders got everything you need.
}

public void getFolders(String directoryName, List<String> folders) {
    File directory = new File(directoryName);
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isDirectory()) {
            folders.add(file.getAbsolutePath());
            getFolders(file.getAbsolutePath(), folders);
        }
    }
}