The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.io  [35 examples] > Directories  [6 examples]

e33. 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);
        }
    }

 Related Examples
e28. Getting the Current Working Directory
e29. Creating a Directory
e30. Deleting a Directory
e31. Listing the Files or Subdirectories in a Directory
e32. Listing the File System Roots

See also: Encodings    Filenames and Pathnames    Files    Parsing    Reading and Writing    Serialization   


© 2002 Addison-Wesley.