javafilerecursiondata-structuresfilefilter

Unable to add Files to List after recursion Java


I wasn't quite sure how to title this question, but I've got some sort of bug that I am not really understanding.

I have a method which recursively searches the subdirectories labeled 'calculation' of a root directory for it's file contents. And it seems to work when I print to console. However, when I try to add these files to a List of Files, it seems not to work, size is 0...

How can I add these files to a List or File[] or any type of data structure so I can process them?

Here is my code:

public static List<File> walkDirectory(String path) {

    List<File> fileList = new ArrayList<File>();

    File root = new File(path);
    File[] list = root.listFiles();

    if (list == null) return null;

    for (File f : list) {

        if (f.isDirectory()) {
            walkDirectory(f.getAbsolutePath());
        } 

        else if (f.getParentFile().getName().contains("calculation")) {
            fileList.add( f ); // does not work...
            System.out.println("File: " + f.getAbsoluteFile());

        }
    }

    return fileList;
}

public static void main(String[] args) {
    System.out.println(FileWalker.walkDirectory("/path/to/root/directory").size()); // size is 0
}

Solution

  • Move this line List<File> fileList = new ArrayList<File>(); to outside of walkDirectory function. What is happening here is you are creating a new fileList variable everytime whenever you are calling function.

    Either make fileList private static variable of class or pass List argument in function itself.