Discuss / Java / 遍历目录结构

遍历目录结构

Topic source

castig

#1 Created at ... [Delete] [Delete and Lock User]

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;

public class Main {

public static void main(String[] args) throws IOException {

String path_in = ".";
if (args.length != 0) {

path_in = args[0];
}

File f = new File(path_in);
printFiles(f, 0);
}

static int printFiles(File thisDir, int lvl) throws IOException {

if (lvl == 0) {

System.out.println(" ".repeat(lvl) + thisDir.getCanonicalPath());
}

File[] fs1 = thisDir.listFiles();
if (fs1 == null) {

return 0;
}

for (File f : fs1) {

String[] str_tmp = f.getCanonicalPath().trim().split(Matcher.quoteReplacement(File.separator));
if (f.isFile()) {

System.out.println(" ".repeat(lvl+1) + str_tmp[str_tmp.length-1]);
} else {

System.out.println(" ".repeat(lvl+1) + str_tmp[str_tmp.length-1] + "/");
printFiles(f, lvl+1);
}

}

return 1;
}

}


  • 1

Reply