[Java基础]IO入门之File类

基本上看JDK文档都能看懂、简单参照JDK写了一个类、实现以下功能:

给定指定路径、显示该路径下所有目录名和文件名(包括子目录)、并且按照目录显示在前、文件显示在后的原则(基本显示样子和Windows一致)、主要代码:

 1 import java.io.File;
2 import java.io.FileFilter;
3
4 //包含递归以及File类的常见操作
5
6 //演示以Windows的树形结构显示目录结构
7 public class FileDemo {
8 // 输出缩进格式
9 public static void printSpace(int deepin) {
10 for (int i = 0; i < deepin; i++)
11 System.out.print("\t");
12 }
13
14 /**
15 * 显示指定目录或文件下的所有目录或文件名(包括子目录)
16 * @param file 要显示的路径File对象
17 * @param deepin 当前路径深度、传1即可、用于控制显示格式的缩进
18 */
19 public static void printFiles(File file, int deepin) {
20
21 // 如果目录则递归
22 if (file.isDirectory()) {
23 // 获得文件夹
24 for (File f : file.listFiles(new FileFilter() { //这里使用了 策略模式和匿名内部类
25
26 @Override
27 public boolean accept(File pathname) {
28 // TODO Auto-generated method stub
29 return pathname.isDirectory();
30 }
31 })) {
32 printSpace(deepin);
33 System.out.println("├" + f.getName());
34 printFiles(f, deepin + 1);
35 }
36
37 // 获得文件
38 for (File f : file.listFiles(new FileFilter() {
39
40 @Override
41 public boolean accept(File pathname) {
42 // TODO Auto-generated method stub
43 return pathname.isFile();
44 }
45 })) {
46 printSpace(deepin);
47 System.out.println("├" + f.getName());
48 }
49 } else {
50 printSpace(deepin);
51 // 如果不是目录 则直接输出文件名
52 System.out.println(file.getName());
53 }
54 }
55
56 public static void main(String[] args) {
57 printFiles(new File("G:/Web"), 1);
58 }
59 }



My New Blog : http://blog.fdlife.info/ The more you know, the less you believe.
原文地址:https://www.cnblogs.com/ForDream/p/2340702.html