使用File类的list方法遍历指定目录下的所有目录
完整代码
import java.io.*;class Main {public static void main(String[] args) {File dir = new File("D:");File[] files = dir.listFiles();FileFilter fileFilter = new FileFilter() {public boolean accept(File file) {return file.isDirectory();}};files = dir.listFiles(fileFilter);System.out.println(files.length);if (files.length == 0) {System.out.println("目录不存在或它不是一个目录");}else {for (int i=0; i< files.length; i++) {File filename = files[i];System.out.println(filename.toString());}}}
}
结果输出
8
D:\sumbile text
D:\idea
D:\movie
D:\test.txt
D:\wechart
D:\music
D:\software
D:\workspace
只获取输出指定目录下的文件夹
完整代码
public class Main { public static void main(String[] args) throws Exception { File file = new File("//Users//zhangshuhang//Desktop"); getAllDirectory(file);
}
public static void getAllDirectory(File file) {//创建过滤器 File[] f = file.listFiles(new GetAllDirectory()); for (File f1 : f) { System.out.println(f1);//判断目录是否为空 if (f1.length() != 0) getAllDirectory(f1); } }
}class GetAllDirectory implements FileFilter {public boolean accept(File pathname) {// 去除所有非文件夹if (pathname.isDirectory()) {return true;}return false;}
}