views:

633

answers:

7

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the framework or nio

+2  A: 

I think this should do the work:

File dir = new File(dirname);
String[] files = dir.list();

This way you have files and dirs. Now use recursion and do the same for dirs (File class has isDirectory() method).

Michał Niklas
+8  A: 

FileUtils have iterateFiles and listFiles methods. Give them a try. (from commons-io)

Bozho
+2  A: 

just write it yourself using simple recursion:

public List<File> addFiles(List<File> files, File dir)
{
    if (files == null)
        files = new LinkedList<File>();

    if (!dir.isDirectory())
    {
        files.add(dir);
        return files;
    }

    for (File file : dir.listFiles())
        addFiles(files, file);
    return files;
}
pstanton
Bozho's answer is better though.
pstanton
Please! let the caller initialize the files list so it hasn't have to check its nullity each time. If you want create a second (public) method that creates the list, calls this internal method and returns the complete list.
helios
@pstanton: so vote for it! :)
helios
whatever. a null check isn't very expensive, convenience + personal preference aside i think he'll get the point.
pstanton
i did vote for it you goose.
pstanton
+3  A: 

I would go with something like:

public void list(File file) {
    System.out.println(file.getName());
    File[] children = file.listFiles();
    for (File child : children) {
        list(child);
    }
}

The System.out.println is just there to indicate to do something with the file. there is no need to differentiate between files and directories, since a normal file will simply have zero children.

Stefan Schmidt
+5  A: 

Ready to run

public class Filewalker {

    public void walk( String path ) {

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

        for ( File f : list ) {
            if ( f.isDirectory() ) {
                walk( f.getAbsolutePath() );
                System.err.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
                System.err.println( "File:" + f.getAbsoluteFile() );
            }
        }
    }

    public static void main(String[] args) {
        Filewalker fw = new Filewalker();
        fw.walk("c:\\" );
    }
}
stacker
+1  A: 

NIO in Java 7 will have something like that:

If you provide a starting point and a file visitor, it will invoke various methods on the file visitor as it walks through the file in the file tree. We expect people to use this if they are developing a recursive copy, a recursive move, a recursive delete, or a recursive operation that sets permissions or performs another operation on each of the files.

yawn
You can get the current snapshot of Java7 and try it out:http://java.sun.com/docs/books/tutorial/essential/io/walk.html
Helper Method
A: 
sateesh