Java_File类讲解_打印目录树状结构_递归算法

时间:2022-05-19 22:12:07
 1 package cn.xiaocangtian.testFile;
 2 
 3 import java.io.File;
 4 
 5 public class FileTree {
 6     public static void main(String[] args) {
 7         File f = new File("E:/Java_All_Code/TestFile/src/cn/xiaocangtian/testFile");
 8         printFile(f, 0);
 9     }
10 
11     static void printFile(File file, int level) {
12         // TODO Auto-generated method stub
13         for (int i = 0; i < level; i++) {
14             System.out.print("-");
15         }
16         System.out.println(file.getName());
17         
18         //如果是目录
19         if (file.isDirectory()) {
20             File[] files = file.listFiles();
21             //遍历目录下的全部文件
22             for (File temp : files) {
23                 printFile(temp, level + 1);
24             }
25                 
26         }
27     }
28     
29 }