DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Recursively Listing All Files Below A Directory

  • submit to reddit
        // description of your code here
Simple iterator to iterate over all non-directory files the lie below a given directory. Demonstrates a use case for the FlatteningIterator snippet. 

package playground.library.files;

import java.util.Arrays;
import java.util.Iterator;
import playground.library.functional.iterator.FlatteningIterator;

 * Iterates over all non-directory files contained in some subdirectory of the 
 * current one.
 * @author david
public class RecursiveFileListIterator implements Iterator<File>
    private final FlatteningIterator flatteningIterator;
    public void remove() { } 
    public RecursiveFileListIterator(File file, FileFilter filter){
        this.flatteningIterator = new FlatteningIterator(new FileIterator(file, filter)); }
    public RecursiveFileListIterator(File file){
        this(file, null);}
    public boolean hasNext(){ 
        return flatteningIterator.hasNext();}
    public File next(){ 
        return (File);}
     * Iterator to iterate over all the files contained in a directory. It returns
     * a File object for non directories or a new FileIterator obejct for directories.
    private static class FileIterator implements Iterator<Object>
        private final Iterator<File> files;
        private final FileFilter filter;
        FileIterator(File file, FileFilter filter){ 
            this.files = Arrays.asList(file.listFiles(filter)).iterator();
            this.filter = filter;}
        public void remove() { }
        public Object next(){
            File next =;
            if (next.isDirectory()) return new FileIterator(next, this.filter);
            else return next;}
        public boolean hasNext(){
            return this.files.hasNext();}       



Snippets Manager replied on Tue, 2010/11/09 - 8:28am

FileUtils from Apache Commons also offers such an iterator...