DirList.java Source code

Java tutorial

Introduction

Here is the source code for DirList.java

Source

import java.io.File;
import java.util.Scanner;

public class DirList {
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("\nEnter a path: ");
        String path = sc.nextLine();
        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory())
            System.out.println("\nThat directory doesn't exist.");
        else {
            System.out.println("\nListing directory tree of:");
            System.out.println(dir.getPath());
            listDirectories(dir, "  ");
        }
    }

    private static void listDirectories(File dir, String indent) {
        File[] dirs = dir.listFiles();
        for (File f : dirs) {
            if (f.isDirectory()) {
                System.out.println(indent + f.getName());
                listDirectories(f, indent + "  ");
            }
        }
    }
}