Discuss / Java / 这样写应该简洁一点吧?

这样写应该简洁一点吧?

Topic source

日落有星

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {

	public static void main(String[] args) throws IOException {
		File currentDir = new File(".");
		String tree = "";
		listDir(currentDir.getCanonicalFile(),tree);
	}

	static void listDir(File dir, String t) {
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (File f : fs) {
				System.out.println(t+f.getName());
				listDir(f,t+" ");
			}
		}
	}
}

得到输出:

.classpath
.project
bin
 .gitignore
 com
  itranswarp
   learnjava
    Main.class
src
 com
  itranswarp
   learnjava
    Main.java

Eagle9988

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

加上文件夹判断再执行是不是更有效率一点呢?

    static void listDir(File dir, String t) {        File[] fs = dir.listFiles();        if (fs != null) {            for (File f : fs) {                    System.out.println(t+f.getName());                    if (f.isDirectory())                    listDir(f, t+"\t");                }            }        }}

  • 1

Reply