Traversing the Files and Directories Under a Directory - Java File Path IO

Java examples for File Path IO:Directory

Description

Traversing the Files and Directories Under a Directory

Demo Code

import java.io.File;

public class Main {
  // Process all files and directories under dir
  public static void visitAllDirsAndFiles(File dir) {
    System.out.println(dir);//w w w . ja  v a 2s  .  c o m

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

  // 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]));
      }
    }
  }

  // Process only files under dir
  public static void visitAllFiles(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        visitAllFiles(new File(dir, children[i]));
      }
    } else {
      System.out.println(dir);
    }
  }
}

Related Tutorials