Java I/O How to - Traverse all files and directories under dir








Question

We would like to know how to traverse all files and directories under dir.

Answer

/*w  w  w  .  ja v a2 s.com*/
import java.io.File;

public class Main {
  public static void main(String[] argv) throws Exception {
     visitAllDirsAndFiles(new File("c:/"));
  }

  
  public static void visitAllDirsAndFiles(File dir) {
    System.out.println(dir);

    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        visitAllDirsAndFiles(new File(dir, children[i]));
      }
    }
  }

}

The code above generates the following result.