HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Walk a directory tree recursively

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
directorywalktreerecursively

Problem

Any suggestions are welcome.

package je3.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IDEA on 31/01/15.
 */
public class DirWalker {
    private List recursiveList = new ArrayList();

    public void walkDir(String pathname) {
        File d = new File(pathname);
        recursiveList.add(d);
        if(d.isDirectory()) {
            for(String f : d.list()) {
                walkDir(f);
            }
        }
    }

    public void reset() {
        recursiveList.clear();
    }

    public List getRecursiveList() {
        return recursiveList;
    }

    public static void main(String[] args) {
        DirWalker dirWalker = new DirWalker();
        dirWalker.walkDir("/tmp");
        dirWalker.getRecursiveList().forEach(System.out::println);
    }
}

Solution

It's simpler to just return the result immediately then need another method.

Also the caller is probably going to need them as File objects eventually so lets just return them as those.

Then there are 2 options, just return a List and use addAll each recursion step:

public List walkDir(File pathname) {
    if(pathname.isDirectory()) {
        List files = new ArrayList();
        files.add(pathname);
        for(File f : pathname.listFiles()) {
            filed.addAll(walkDir(f));
        }
        return files;
    }else{
        return Collections.singletonList(pathname);
    }
}


Or use a private recursive method where you pass in a accumulator List:

private void walkDirRecurse(File pathname, List files) {
    if(pathname.isDirectory()) {
        for(File f : pathname.listFiles()) {
            files.add(f);
            walkDirRecurse(f, files);
        }
    }
}

Code Snippets

public List<File> walkDir(File pathname) {
    if(pathname.isDirectory()) {
        List<File> files = new ArrayList();
        files.add(pathname);
        for(File f : pathname.listFiles()) {
            filed.addAll(walkDir(f));
        }
        return files;
    }else{
        return Collections.singletonList(pathname);
    }
}
private void walkDirRecurse(File pathname, List<File> files) {
    if(pathname.isDirectory()) {
        for(File f : pathname.listFiles()) {
            files.add(f);
            walkDirRecurse(f, files);
        }
    }
}

Context

StackExchange Code Review Q#79202, answer score: 3

Revisions (0)

No revisions yet.