使用 File 类的 dir.isDirectory() 和 dir.list() 方法来遍历目录
完整代码
import java.io.File;public class Main {public static void main(String[] argv) throws Exception {System.out.println("遍历目录");File dir = new File("/software/java"); //要遍历的目录visitAllDirsAndFiles(dir);}public static void visitAllDirsAndFiles(File dir) {System.out.println(dir);if (dir.isDirectory()) {String[] children = dir.list();for (int i = 0; i < children.length; i++) {visitAllDirsAndFiles(new File(dir, children[i]));}}}
}
结果输出
遍历目录
/software/java
/software/java/Car.class
/software/java/FileUtil.class
/software/java/FileUtil.java
/software/java/HelloWorld.class
/software/java/HelloWorld.java
/software/java/HelloWorldDebug.class
/software/java/HelloWorldDebug.java
/software/java/test.xml
/software/java/login.jsp