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 - 10:09am by shyam (not verified)

wonderful it was help!

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

Thanks, it helped a lot :)

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.