package com.itranswarp.learnjava; import java.io.File; import java.io.IOException; /** * Learn Java from https://www.liaoxuefeng.com/ * * @author liaoxuefeng */ public class Main { public static void main(String[] args) throws IOException { File currentDir = new File("."); listDir(currentDir.getCanonicalFile(), 0); } static void listDir(File dir, int depth) { // TODO: 递归打印所有文件和子文件夹的内容 if (!dir.isFile() && !dir.isDirectory()) { return; } StringBuilder sb = buildBlank(depth); if (dir.isDirectory()) { System.out.println(sb.toString() + dir.getName() + '/'); File[] fs = dir.listFiles(); for (File f: fs) { listDir(f, depth + 1); } } if (dir.isFile()) { System.out.println(sb.toString() + dir.getName()); } return; } static StringBuilder buildBlank(int depth) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < depth; i++) { sb.append(' '); } return sb; } }
Sign in to make a reply
给你点赞1232