简体   繁体   中英

what's wrong with my Recursion

I want to implement a method that find all the files in a folder and its sub folders and so on... I have implemented it by recursion but i don't know what is wrong. can someone help me?

private void fileLister(){
    File d = new File(adress);
    File[] existingFiles =d.listFiles();
    for(int i = 0;i<existingFiles.length;i++){

        if(existingFiles[i].isDirectory()){

            fileLister();

        }
        else{

            List<File> templist = Arrays.asList(existingFiles);
                allExsistingFiles.addAll(templist);
        }
    }
}

You need each call to the recursive method to have the directory you are working in that call. The minimal change should be:

    private void fileLister(File directory){
    File[] existingFiles =directory.listFiles();
    for(int i = 0;i<existingFiles.length;i++){

        if(existingFiles[i].isDirectory()){

            fileLister(existinFiles[i]);

        }
        else{

            List<File> templist = Arrays.asList(existingFiles);
                allExsistingFiles.addAll(templist);
        }
    }
}

Check IT:

public void showAll(String directoryName, ArrayList<File> files) {
    File dir = new File(directoryName);

    File[] fL = dir.listFiles();
    for (File file : fL) {
        if (file.isFile()) {
            files.add(file);
        } else if (file.isDirectory()) {
            listf(file.getAbsolutePath(), files);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM