代码
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("./Documents"); // 所需文件已手动创建在本地目录 System.out.println("Documents/"); listDir(currentDir.getCanonicalFile()); } static int depth = 1; static void listDir(File dir) { // TODO: 递归打印所有文件和子文件夹的内容 File[] fs = dir.listFiles(); String blank = " "; blank = blank.repeat(depth); if (fs != null) { for (File f : fs) { if (f.isDirectory()) { System.out.println(blank + f.getName() + "/"); depth ++; listDir(f); depth --; } if (f.isFile()) { System.out.println(blank + f.getName()); } } } } }
输出
Documents/ other/ ppt/ word/ 1.docx 2.docx work/ abc.doc
该方法打印当前目录,第一级目录会有空格,格式有差异
Sign in to make a reply
D
代码
输出