Java深度遍历文件夹(递归实现)

时间:2023-12-22 08:29:08
 package FileDemo;

 import java.io.File;

 public class DeepSearchDir {

     /**
* @param args
*/
public static void main(String[] args) {
File dir=new File("F:\\"); listDir(dir,0);
} private static void listDir(File dir,int level) {
System.out.println(getspace(level)+dir.getName());
File files[]=dir.listFiles();
level++;
for(File f:files){
if(f.isDirectory()){
listDir(f,level);
}
else {
System.out.println(getspace(level)+f.getName());
}
}
} private static String getspace(int level) { StringBuilder sb=new StringBuilder();
sb.append("|--");
for(int x=0;x<level;x++){
sb.insert(0," ");
}
return sb.toString();
} }