Sunday, 24 April 2016

How to traverse a directory using recursion ?


Example
Traverse a directory recursively and display its contents

public static void main (String args[]) {
  display(new File("C:\\Downloads"));
}

public static void display(File node) {
  // print file path
  System.out.println(node.getAbsoluteFile());

  // if a directory found, again display its contents using recursion
  if (node.isDirectory()) {
    String[] subNodes = node.list();

    for(String filename : subNodes) {
      // File to display = file path + file name
      display(new File(node, filename));
    }
  }

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.