Recursion 发表于 2018-08-30 | 分类于 技术 Recursion Recursion 所谓递归(Recursion),就是方法调用自身。对于递归来说,一定有一个出口,让递归借宿,只有这样才能保证不出现死循环。 1234567891011121314151617181920212223242526272829303132333435363738394041424344public class Test { public int compute(int numnber) { if (numnber == 1) { return 1; } else { return numnber * compute(numnber - 1); } } public static void main(String[] args) { Test test = new Test(); System.out.println(test.compute(5)); }}public class FileTest { public static void deleteAll(File file) { if (file.isFile() || file.list().length == 0) { file.delete(); } else { File[] files = file.listFiles(); for (File file1 : files) { deleteAll(file1); file.delete(); } } } public static void main(String[] args) { File file = new File("/Users/bob/Downloads/activiti-5.16.41"); deleteAll(file); }} 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485/** * 循环遍历文件夹 */public class ListAllTest { //用于判断目录或文件所处的层次 private static int time; public static void deepList(File file) { if (file.isFile() || file.listFiles().length == 0) { return; } else { File[] files = file.listFiles(); files = sort(files); for (File file1 : files) { StringBuffer stringBuffer = new StringBuffer(); if (file1.isFile()) { stringBuffer.append(getTabs(time)); stringBuffer.append(file1.getName()); } else { stringBuffer.append(getTabs(time)); stringBuffer.append(file1.getName()); stringBuffer.append("\\"); } System.out.println(stringBuffer.toString()); if (file1.isDirectory()) { time++; deepList(file1); time--; } } } } //整理文件数组,使得目录排在文件之前 private static File[] sort(File [] files){ List<File> list = new ArrayList<>(); for (File file : files) { if (file.isDirectory()) { list.add(file); } } for (File file : files) { if (file.isFile()) { list.add(file); } } return list.toArray(new File[files.length]); } //判断需要加多少个tab private static String getTabs(int time) { StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < time; i++) { stringBuffer.append("\t"); } return stringBuffer.toString(); } public static void main(String[] args) { File file = new File("/Users/bob/Downloads/activiti-5.16.4"); deepList(file); }}