一、递归思想
二、目录层级的表示
package com.java.io;
import java.io.*;
import java.io.File;
public class DirTree {
private int fileLevel;
/**
* 输出初始给定的目录
* @param dirPath
*/
public void printDir(String dirPath) {
String[] dirNameList = dirPath.split("\\\\");
// 设定文件level的最初的层级
fileLevel = dirNameList.length;
for (int i = 0; i < dirNameList.length; i++) {
System.out.println(createFileName(dirNameList[i], i));
}
}
/**
* 创建目录名称,带缩进
* @param name
* @param level
* @return
*/
public String createFileName(String name, int level) {
String fileNameStr = "";
// 按层次进行缩进
for (int i = 0; i < level; i++) {
fileNameStr = fileNameStr + " ";
}
fileNameStr = fileNameStr + "- " + name;
return fileNameStr;
}
private void createDirTree(String filePath) {
File file = new File(filePath);
// 取得代表目录中所有文件的File对象数组
File[] list = file.listFiles();
// 遍历file数组
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
System.out
.println(createFileName(list[i].getName(), fileLevel));
int tempLever = fileLevel;
fileLevel++;
// 递归子目录
createDirTree(list[i].getPath());
fileLevel = tempLever;
} else {
System.out
.println(createFileName(list[i].getName(), fileLevel));
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String pathname = "D:/java再学习";
DirTree dirTree = new DirTree();
dirTree.printDir(pathname);
dirTree.createDirTree(pathname);
}
}