Over a million developers have joined DZone.

Recursively Listing All Files Below A Directory

// 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.io.File;
import java.io.FileFilter;
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
    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)flatteningIterator.next();}
     * 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
        private final Iterator 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 = this.files.next();
            if (next.isDirectory()) return new FileIterator(next, this.filter);
            else return next;}
        public boolean hasNext(){
            return this.files.hasNext();}       


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}