Java I/O How to - Traverse only directories under dir








Question

We would like to know how to traverse only directories under dir.

Answer

/*from  w  w  w.j a v  a 2s. c o  m*/
import java.io.File;

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

  // Process only directories under dir
  public static void visitAllDirs(File dir) {
    if (dir.isDirectory()) {
      System.out.println(dir);

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

}

The code above generates the following result.