Close

Java - How to iterate files in a directory and subdirectories?

[Updated: May 4, 2017, Created: May 3, 2017]

Java IO & NIO Java 

In this example we will show how to iterate through a given directory and all its subdirectories.

Our example directory structure:

d:>tree d:\test /F /A
Folder PATH listing for volume Data
Volume serial number is 68F9-EDFA
D:\TEST
| one.txt
| two.txt
|
+---testDir1
| | four.txt
| | three.txt
| |
| \---testDir12
| five.txt
| six.txt
|
\---testDir2
| eight.txt
| seven.txt
|
\---testDir12
nine.txt
ten.txt

Following fetchFiles(..) method will callback the specified fileConsumer with each file in the provided dir and sub-directories:

public class IterateFilesExample {

  public static void fetchFiles(File dir, Consumer<File> fileConsumer) {

      if (dir.isDirectory()) {
          for (File file1 : dir.listFiles()) {
              fetchFiles(file1, fileConsumer);
          }
      } else {
          fileConsumer.accept(dir);
      }
  }

  public static void main(String[] args) {
      File file = new File("d:\\test");
      fetchFiles(file, f -> System.out.println(f.getAbsolutePath()));
  }
}

Output

d:\test\one.txt
d:\test\testDir1\four.txt
d:\test\testDir1\testDir12\five.txt
d:\test\testDir1\testDir12\six.txt
d:\test\testDir1\three.txt
d:\test\testDir2\eight.txt
d:\test\testDir2\seven.txt
d:\test\testDir2\testDir12\nine.txt
d:\test\testDir2\testDir12\ten.txt
d:\test\two.txt

Client code can read file contents or apply any logic in Consumer<File>.

See Also