利用File對象列出指定目錄下的所有子目錄和文件,并按層次打印悴品。如果不指定參數(shù)白对,則使用當(dāng)前目錄掠廓,如果指定參數(shù),則使用指定目錄甩恼。
如:
Documents/
word/
1.docx
2.docx
work/
abc.doc
ppt/
other/
實現(xiàn):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
public class Main {
public static void main(String[] args) throws IOException {
File fs = new File(".");
fs = fs.getCanonicalFile();
if (args.length > 0) {
fs = new File(args[0]);
if (!fs.exists()) {
throw new FileNotFoundException(args[0]);
}
}
String[] splitPaths = fs.toString().split("\\\\");
for (int i = 0; i < splitPaths.length - 1; i++) {
System.out.println(" ".repeat(i) + splitPaths[i]);
}
listMyFiles(fs);
}
static void listMyFiles(File fs) {
StringBuilder space = new StringBuilder();
space.append(" ".repeat(fs.toString().split("\\\\").length - 1));
if (fs.isDirectory()) {
System.out.println(space + fs.getName() + "/");
File[] dirs = {};
try {
dirs = Objects.requireNonNull(fs.listFiles());
} catch (NullPointerException e) {
System.out.println(space + " " + "\"" + fs + "\" is not support to view!");
}
for (File f : dirs) {
listMyFiles(f);
}
} else if (fs.isFile()) {
System.out.println(space + fs.getName());
}
}
}
效果: