1.使用递归删除某一目录下的全部文件
class="java" name="code">package com.lfl.file; import java.io.File; public class DeleteAllFileTest { public static void deleteAll(File file) { if (file.isFile() || file.list().length == 0) { file.delete(); } else { File[] files = file.listFiles(); for (File f : files) { deleteAll(f); f.delete(); } file.delete(); } } public static void main(String[] args) { File file = new File("G:\\myfirstsite222"); deleteAll(file); } }
?
?
2.使用递归遍历某一目录下的所有文件,并以树形结构显示
package com.lfl.file; import java.io.File; import java.util.ArrayList; import java.util.List; public class ListAllFileTest { private static int level; public static void deepList(File file) { if (file.isFile() || file.list().length == 0) { return; } else { File[] files = file.listFiles(); files = sort(files); for (File f : files) { StringBuilder output = new StringBuilder(); if (f.isFile()) { output.append(getLevel(level)); output.append(f.getName()); } else { output.append(getLevel(level)); output.append(f.getName()); output.append("\\"); } System.out.println(output.toString()); if (f.isDirectory()) { level ++; deepList(f); level --; } } } } public static File[] sort(File[] files) { List<File> list = new ArrayList<File>(); List<File> fileList = new ArrayList<File>(); for (File f : files) { if (f.isDirectory()) list.add(f); else fileList.add(f); } list.addAll(fileList); return list.toArray(new File[files.length]); } public static String getLevel(int level) { StringBuilder sb = new StringBuilder(); for (int i=0; i < level; i++) { sb.append("\t"); } return sb.toString(); } public static void main(String[] args) { File file = new File("G:/222"); deepList(file); } }
?
?