Traversing the Files and Directories Under a Directory

This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir public static void visitAllDirsAndFiles(File dir) { process(dir); 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()) { process(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 { process(dir); } }

Comments

22 Jan 2010 - 11:09am by shyam (not verified)

wonderful it was help!

3 Feb 2010 - 4:30am by Anonymous (not verified)

Thanks, it helped a lot :)

12 Feb 2010 - 6:50am by Anonymous (not verified)

thank you. It does help a lot!

3 May 2010 - 1:27pm by Anonymous (not verified)

Thank you, it really helped :) Very simple, although not that obvious snippets for a starter like me :)

3 May 2010 - 1:27pm by Anonymous (not verified)

Thank you, it really helped :) Very simple, although not that obvious snippets for a starter like me :)

13 May 2010 - 4:11pm by David Liou Chen (not verified)

These are great examples... very helpful.

8 Jun 2010 - 11:40am by Anonymous (not verified)

Very Helpful....

10 Jun 2010 - 9:29am by Anonymous (not verified)

its good:)

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.