Discuss / Java / 作业

作业

Topic source

保证调用函数时参数最简

import java.io.File;

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

	static void listDir(File dir) {
		printName(dir, 1);
	}
	
	static void printName(File dir, int level) {
        //获取文件级别,生成空格
		StringBuilder sp = new StringBuilder("");
		for(int i=1; i<level; i++) {
			sp.append("  ");
		}

        //打印空格及文件名,若为目录加入"\"
		System.out.print(sp.toString()+dir.getName());
		if (dir.isDirectory()) {
			System.out.println("\\");
		}else {
			System.out.println();
		}
		
        //获取子目录及子文件,有子目录则进行递归
		File[] fs = dir.listFiles();
		if (fs != null) {
			for(File f:fs) {
				printName(f, level+1);
			}
		}
	}
	
}

ANGERIED

#2 Created at ... [Delete] [Delete and Lock User]
兄弟,你这写法很牛啊,学习了。 我思考了一下,我个人称你这个方法为“看到什么打印什么”或者“一站到底”。
我认为,你的写法简洁得原因就是,无论文件或是文件夹都统一处理,而不是考虑在“找不出文件夹”这一操作后,在进行分支处理。
这是我的个人总结,如有错误,请指教

summer_T1

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

参照你的,又改出一个更简洁的

public class Main {   static int cnt = 0;   public static void main(String[] args) {      File path = new File("/Users/mac/IdeaProjects/study");      printFile(path, 1);   }   static void printFile(File dir, int level) {      StringBuilder sp = new StringBuilder();      for (int i = 1; i < level; i++) {         sp.append("    ");      }      System.out.println(sp + dir.getName() + (dir.isDirectory() ? "/" : ""));      //列出目录下的文件和子目录名      File[] fs = dir.listFiles();      if (fs != null) {         for (File f : fs) {            printFile(f, level + 1);         }      }   }   }

summer_T1

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

参照你的,又改出一个更简洁的

public class Main {
	static int cnt = 0;

	public static void main(String[] args) {
		File path = new File("/Users/mac/IdeaProjects/study");
		printFile(path, 1);
	}

	static void printFile(File dir, int level) {
		StringBuilder sp = new StringBuilder();
		for (int i = 1; i < level; i++) {
			sp.append("    ");
		}
		System.out.println(sp + dir.getName() + (dir.isDirectory() ? "/" : ""));
		//列出目录下的文件和子目录名
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (File f : fs) {
				printFile(f, level + 1);
			}
		}
	}
	
}


  • 1

Reply