Java Notes

Example - Recursive List

Here is an example of listing files and directories recursively.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
// File   : io/file/RecusiveList.java
// Purpose: Recursively list directories and files.
// Author : Fred Swartz 1997-08-06 (Bangkok, Thailand), 2000-10-31 (Rota, Spain)
//                      2006-09-25 (Rodenbach, Deutschland)

import java.util.*;
import java.io.*;

public class RecursiveList {
    static final int      MAX_DEPTH  = 20;  // Max 20 levels (directory nesting)
    static final String   INDENT_STR = "   ";                 // Single indent.
    static final String[] INDENTS    = new String[MAX_DEPTH]; // Indent array.

    //===================================================================== main
    public static void main(String[] args) {
        //... Initialize array of indentations.
        INDENTS[0] = INDENT_STR;
        for (int i = 1; i < MAX_DEPTH; i++) {
           INDENTS[i] = INDENTS[i-1] + INDENT_STR;
        }

        System.out.print("Enter a directory name to list recursively:");
        Scanner in = new Scanner(System.in);
        File root = new File(in.nextLine());
        if (root != null && root.isDirectory()) {
            listRecursively(root, 0);
        } else {
            System.out.println("Not a directory: " + root);
        }
    }


    //========================================================== listRecursively
    public static void listRecursively(File fdir, int depth) {
        System.out.println(INDENTS[depth] + fdir.getName());  // Print name.

        if (fdir.isDirectory() && depth < MAX_DEPTH) {
            for (File f : fdir.listFiles()) {  // Go over each file/subdirectory.
                listRecursively(f, depth+1);
            }
        }
    }
}