在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