Java如何列印目錄的層次結構?

2019-10-16 22:29:40

在Java程式中,如何列印目錄的層次結構?

以下範例顯示如何使用File類的file.getName()file.listFiles()方法列印指定目錄的層次結構。

package com.yiibai;

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

public class DirectoryHierarchy {
    public static void main(String[] a) throws IOException {
        showDir(1, new File("F:\\worksp\\javaexamples\\java_directories"));
    }

    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 + 2, files[i]);
        }
    }
}

執行上面範例程式碼,得到以下結果 -

--java_directories
----.classpath
----.project
----bin
------com
--------yiibai
----------CreateDirectories.class
----------DeleteDirectory.class
----------DirectoryHierarchy.class
----------EmptyDirectory.class
----------HiddenDirectory.class
----------HiddenDirectory2.class
----dir11
------dir12
--------dir13
------file1 - 副本.txt
------file1.txt
----myfile.txt
----src
------com
--------yiibai
----------CreateDirectories.java
----------DeleteDirectory.java
----------DirectoryHierarchy.java
----------EmptyDirectory.java
----------HiddenDirectory.java
----------HiddenDirectory2.java

範例-2

以下是Java中列印目錄的層次結構的另一個例子。

package com.yiibai;

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

public class DirectoryHierarchy2 {
    public static void main(String[] a) throws IOException {
        showDir(1, new File("F:\\worksp\\javaexamples\\java_directories"));
    }

    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 + 2, files[i]);
        }
    }
}

執行上面範例程式碼,得到以下結果 -

-java_directories
---.classpath
---.project
---bin
-----com
-------yiibai
---------CreateDirectories.class
---------DeleteDirectory.class
---------DirectoryHierarchy.class
---------DirectoryHierarchy2.class
---------EmptyDirectory.class
---------HiddenDirectory.class
---------HiddenDirectory2.class
---dir11
-----dir12
-------dir13
-----file1 - 副本.txt
-----file1.txt
---myfile.txt
---src
-----com
-------yiibai
---------CreateDirectories.java
---------DeleteDirectory.java
---------DirectoryHierarchy.java
---------DirectoryHierarchy2.java
---------EmptyDirectory.java
---------HiddenDirectory.java
---------HiddenDirectory2.java