import java.io.File; public class TestFileInteration { static String endString = "|__"; //结尾字符串,用来形象显示层次关系 public static void main(String[] args) { File f = new File("F:/A"); //假设要列出 F:/A 下的文件(夹) System.out.println("---" + f.getName()); treefiles(f, 1); } /** * * @param f1 文件(夹)路径的对象 * @param level 进入一个目录,加一层 */ public static void treefiles(File f1, int level) { String preString = ""; for (int i = 0; i < level; i++) { preString = " " + preString; //每增加一层,加三个空格和结尾字符串 |__ } preString += endString; //加上结尾字符串 |__ if (f1.isDirectory()) { File[] f2 = f1.listFiles(); for (int i = 0; i < f2.length; i++) { String temp = preString + f2[i].getName(); System.out.println(temp); if (f1.isDirectory()) sfiles(f2[i], level + 1); //递归调用 } } } }
结果如下:
---A |__B |__E |__G |__工作表.xlsx |__H.txt |__F |__图图.psd |__C |__I |__J.txt |__D.txt |__新建.docx