Listing 10: ListAllFiles.java — Lists a subdirectory recursively

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

class ListAllFiles
{
    static int indentLevel = 0;
    
    public static void main(String[] args)
        throws IOException
    {
        if (args.length > 0)
            list(new File(args[0]));
        else
            list(new File(
                 System.getProperty(
                     "user.dir")));
    }

    static void list(File dir)
        throws IOException
    {
        ++indentLevel;
        File[] files = dir.listFiles();
        for (int i=0; i < files.length; ++i)
        {
            display(files[i].getName());
            if (files[i].isDirectory())
                list(files[i]);
        }
        --indentLevel;
    }
    
    static void display(String name)
    {
        for (int i=0; i < indentLevel; ++i)
            System.out.print("    ");
        System.out.println(name);
    }
}

/* Output:
    Compare.java
    Employee.java
    employees.dat
    FileViewer.java
    FindFile.java
    ListAllFiles.class
    ListAllFiles.java
    ListFiles.java
    ListSomeFiles.java
    LogFile.java
    logfile1.txt
    LogFileTest.java
    ProcessRecords.java
    PropTest.java
    records.c
    Stack.java
    temp
        bar
        baz
        foo
    Test.java
    ViewFile.java
*/
— End of Listing —