在Java程序中,如何遍历目录?
以下示例演示如何通过File
类的dir.isDirectory()
和dir.list()
方法遍历目录。
package com.yiibai;
import java.io.File;
import java.io.IOException;
public class TraversingDirectory {
public static void main(String[] argv) throws Exception {
System.out.println("The Directory is traversed.");
String dir = "F:/worksp/javaexamples/java_directories";
File file = new File(dir);
visitAllDirsAndFiles(file, 0);
}
static void visitAllDirsAndFiles(File file, int indent) 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++)
visitAllDirsAndFiles(files[i], indent + 2);
}
}
}
执行上面示例代码,得到以下结果 -
The Directory is traversed.
-java_directories
---.classpath
---.project
---bin
-----com
-------yiibai
---------CreateDirectories.class
---------DeleteDirectory.class
---------DirectoryHierarchy.class
---------DirectoryHierarchy2.class
---------DirectoryModificationTime.class
---------DirectoryModificationTime2.class
---------DirectorySize.class
---------DirectorySize2.class
---------EmptyDirectory.class
---------HiddenDirectory.class
---------HiddenDirectory2.class
---------ParentDirectory.class
---------ParentDirectory2.class
---------SearchingFiles.class
---------SearchingFiles2.class
---------TraversingDirectory.class
---dir11
-----dir12
-------dir13
-----file1 - 副本.txt
-----file1.txt
---myfile.txt
---src
-----com
-------yiibai
---------CreateDirectories.java
---------DeleteDirectory.java
---------DirectoryHierarchy.java
---------DirectoryHierarchy2.java
---------DirectoryModificationTime.java
---------DirectoryModificationTime2.java
---------DirectorySize.java
---------DirectorySize2.java
---------EmptyDirectory.java
---------HiddenDirectory.java
---------HiddenDirectory2.java
---------ParentDirectory.java
---------ParentDirectory2.java
---------SearchingFiles.java
---------SearchingFiles2.java
---------TraversingDirectory.java