3
\$\begingroup\$

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<File> recursiveList = new ArrayList<File>();

    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<File> getRecursiveList() {
        return recursiveList;
    }

    public static void main(String[] args) {
        DirWalker dirWalker = new DirWalker();
        dirWalker.walkDir("/tmp");
        dirWalker.getRecursiveList().forEach(System.out::println);
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Which version of java are you using? If 7 or above, you could use the nio Files.walkFileTree, and if you're using 8 you could use the version that outputs a Stream \$\endgroup\$
    – Edd
    Commented Jan 31, 2015 at 21:46
  • \$\begingroup\$ Thanks, good to know. This is just an exercise, though. I don't mind reinventing the wheel a bit here. :-) \$\endgroup\$
    – qed
    Commented Jan 31, 2015 at 21:48

1 Answer 1

3
\$\begingroup\$

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<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);
    }
}

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

private void walkDirRecurse(File pathname, List<File> files) {
    if(pathname.isDirectory()) {
        for(File f : pathname.listFiles()) {
            files.add(f);
            walkDirRecurse(f, files);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ d has not been defined in the walkDirRecurse method. \$\endgroup\$
    – qed
    Commented Jan 31, 2015 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.