文章目录
列出文件夹中的文件
使用 tree
命令查看我将要列出的文件夹中的文件:
PS D:\F\CAM> tree /a /f
文件夹 PATH 列表
卷序列号为 8C71-860C
D:.
\---note
+---CAM350 - 导入光绘(GERBER)文件
| CAM350 - 导入光绘(GERBER)文件.md
| image-20210418133707404.png
| image-20210418133829443.png
| image-20210418134053797.png
| image-20210418134504131.png
| image-20210418134658919.png
|
\---CAM350 - 导出 DXF 文件
CAM350 - 导出 DXF 文件.md
image-20210410164603863.png
image-20210410164625152.png
image-20210410164756490.png
image-20210410164936800.png
image-20210410165257811.png
image-20210410165536242.png
image-20210410170128753.png
image-20210410170251516.png
Java 代码:
import java.io.File;
public class Main {
public static void main(String[] args) {
listFiles(new File("D:\\F\\CAM"), 0);
}
public static void listFiles(File file, int depth) {
if ((file == null) || !file.exists()) {
System.out.println("File does not exist!");
return;
}
StringBuilder indentation = new StringBuilder(4 * depth);
String whitespace = " ";
for (int i = 0; i < (4 * depth); ++i) {
indentation.append(whitespace);
}
if (file.isDirectory()) { // 文件夹
System.out.println(indentation + file.getName() + ": {");
File[] files = file.listFiles(); // 列出所有文件或文件夹
for (File f : files) {
listFiles(f, (depth + 1)); // 递归调用自己
}
System.out.println(indentation + "}");
} else { // 文件
System.out.println(indentation + file.getName());
}
}
}
运行程序,控制台输出:
CAM: {
note: {
CAM350 - 导入光绘(GERBER)文件: {
CAM350 - 导入光绘(GERBER)文件.md
image-20210418133707404.png
image-20210418133829443.png
image-20210418134053797.png
image-20210418134504131.png
image-20210418134658919.png
}
CAM350 - 导出 DXF 文件: {
CAM350 - 导出 DXF 文件.md
image-20210410164603863.png
image-20210410164625152.png
image-20210410164756490.png
image-20210410164936800.png
image-20210410165257811.png
image-20210410165536242.png
image-20210410170128753.png
image-20210410170251516.png
}
}
}