今天,一个网友问了这个问题,下班后就动手写给他了,顺便记录下。哈哈,记得刚学Java那会儿写过这玩意。
package com.billstudy.demo;
import java.io.File;
/**
* Folder recursion show
* @author Bill
* @since V1.0 2015/01/22
*/
public class FileRecursion {
public static void main(String[] args) {
// source file direction
String sourceTargetFilePath = "E:/alibaba";
File sourceTargetFile = new File(sourceTargetFilePath);
System.out.println(sourceTargetFilePath);
recursionFile(sourceTargetFile,0L);
}
/**
* recursion file
* @param file
*/
private static void recursionFile(File file,long level) {
if(file.isFile()){
System.out.println(printFilePath(level) + file.getName());;
}else{
File[] files = file.listFiles();
for (File innerFile : files) {
System.out.println(printFilePath(level) + innerFile.getName());
if(innerFile.isDirectory()){
// continue recursion
level++;
recursionFile(innerFile,level);
level--;
}
}
}
}
/**
* print file path by level
* @param file
* @param level
*/
private static String printFilePath(long level) {
StringBuilder tree = new StringBuilder("|--");
for (int i = 0; i < level; i++)
tree.append("|--");
return tree.toString();
}
}
文件结构:
控制台输出:
遇到文件夹就深入,否则就打印结束递归。