练习参考答案
Topic source改了一天 终于 改完了
package com.itranswarp.learnjava;
import java.io.File;
import java.io.IOException;
/**
* Learn Java from https://www.liaoxuefeng.com/
*
* @author liaoxuefeng
*/
public class Main {
static int count = 0;
public static void main(String[] args) throws IOException {
// File currentDir = new File("C:\\AAAA");
File currentDir = new File(".");
File canonicalFile = currentDir.getCanonicalFile();
System.out.println(canonicalFile);
listDir(currentDir.getCanonicalFile());
}
static void listDir(File dir) throws IOException {
// TODO: 递归打印所有文件和子文件夹的内容
File[] fs = dir.listFiles();
if (fs != null) {
for (int i = 0; i < fs.length; i++) {
//打印第一条文件或目录
File f = fs[i];
if (count > 0 && f.isFile() && i > 0) {
for (int j = 0; j < count; j++) {
System.out.print(" ");
}
}
System.out.println(f.getName());
//目录
if (f.isDirectory()) {
count++;
if ((f.list().length > 0)) {
for (int j = 0; j < count; j++) {
System.out.print(" ");
}
}
listDir(f);
count--;
}
}
}
}
}
- 1
MayEasLau