Easy Tutorial
❮ Java Environment Setup Java Arraylist Foreach ❯

Java Example - Printing Directory Structure

Java Example

The following example demonstrates how to print the directory structure using the file.getName() and file.listFiles() methods of the File class:

Main.java File

import java.io.File;
import java.io.IOException;

public class FileUtil {
    public static void main(String[] a) throws IOException {
        showDir(1, new File("d:\\Java"));
    }
    static void showDir(int indent, File file) throws IOException {
        for (int i = 0; i < indent; i++)
            System.out.print('-');
        System.out.println(file.getName());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++)
                showDir(indent + 4, files[i]);
        }
    }
}

The above code outputs the following result when run:

-Java
-----codes
---------string.txt
---------array.txt
-----w3cschoolcc

Java Example

❮ Java Environment Setup Java Arraylist Foreach ❯