1 import java.io.File;
2 import java.util.ArrayList;
3
4 public class DirFileShow
5 {
6 private static int count = 0;// tab计算器
7 // 通过递归显示文件夹和文件;排序规则为先显示文件夹再显示文件
8
9 public static void doSomething(File file)
10 {
11 // 路径检测是否存在
12 if (!file.exists())
13 {
14 System.out.println("The specified path does not exist.please re-specify path and file.");
15 System.exit(0);
16 }
17 // 实现递归
18 if (null == file.listFiles())// (file.isFile() || 0 ==
19 // file.listFiles().length)递归出口若传入的file对象为文件或空文件夹则return;
20 {
21 return;
22 }
23 else
24 {
25 // 通过sort方法实现文件夹和文件排序并将file数组返回给files
26 File[] files = sort(file.listFiles());
27 // 打印文件树型结构
28 for (File f : files)
29 {
30 String strTab = strTab(count);// 通过strTab方法获得“/t”值赋给strTab
31 StringBuffer fileName = new StringBuffer();
32 if (f.isFile())
33 {
34 fileName.append(strTab);
35 fileName.append(f.getName());
36 System.out.println(fileName.toString());
37 }
38 if (f.isDirectory())
39 {
40 fileName.append(strTab);
41 fileName.append(f.getName());
42 System.out.println(fileName.toString());
43 }
44 count++;
45 doSomething(f);
46 count--;
47 }
48 }
49 }
50
51 // 通过ArrayList集合实现文件夹和文件排序后转换为数组返回调用端
52 private static File[] sort(File[] files)
53 {
54 ArrayList<File> list = new ArrayList<File>();
55 for (File f : files)
56 {
57 if (f.isDirectory())
58 {
59 list.add(f);
60 }
61 }
62 for (File f : files)
63 {
64 if (f.isFile())
65 {
66 list.add(f);
67 }
68 }
69 return list.toArray(files);
70 }
71
72 // 根据cot值增加进位符
73 private static String strTab(int val)
74 {
75 StringBuffer strTab = new StringBuffer();
76 for (int i = 0; i < val; i++)
77 {
78 strTab.append("\t");
79 }
80 return strTab.toString();
81 }
82
83 public static void main(String[] args)
84 {
85 File file = new File("d:/");
86 DirFileShow.doSomething(file);
87 }
88 }