需求:递归遍历一个目录,筛选出需要查找的文件类型 实现:分别用Java流式实现和递归实现 代码:
1package hello; 2 3import java.io.File; 4import java.io.IOException; 5import java.nio.file.FileSystems; 6import java.nio.file.Files; 7import java.nio.file.Path; 8 9/** 10 * Description: 11 * <p> 12 * 13 * @author shuvidora 14 * @date 2019/6/12 12:27 15 */ 16class WalkTree { 17 /** 18 * 流式实现筛选指定目录下指定类型的文件 19 */ 20 public void walkTree() { 21 Path start = FileSystems.getDefault().getPath("src"); 22 try { 23 Files.walk(start) 24 .filter(path -> path.toFile().isFile()) 25 .filter(path -> path.toString().endsWith(".java")) 26 .forEach(System.out::println); 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } 31 32 /** 33 * 默认只扫描当前文件夹 34 * @param f 35 */ 36 public void filterFileType(File f) { 37 filterFileType(f, false); 38 } 39 40 /** 41 * 42 * @param file 43 * @param isRecursive 是否递归子文件夹 44 */ 45 public void filterFileType(File file, boolean isRecursive) { 46 if (file.isDirectory()) { 47 File[] files = file.listFiles(); 48 for (File f : files) { 49 if (f.isFile()) { 50 if (f.getName().endsWith(".java")) { 51 System.out.println(f.getName()); 52 } 53 } else if(isRecursive && f.isDirectory()) { 54 filterFileType(f, true); 55 } 56 } 57 } 58 } 59} 60 61// 枚举实现单例模式,线程安全,非延迟加载 62enum FileUtils { 63 INSTANCE; 64 private WalkTree instance; 65 FileUtils() { 66 instance = new WalkTree(); 67 } // 默认private构造方法 68 public WalkTree getInstance() { 69 return instance; 70 } 71} 72 73public class FileTest { 74 public static void main(String[] args) { 75 FileUtils main = FileUtils.INSTANCE; 76 WalkTree walkTree = main.getInstance(); 77 //walkTree.walkTree(); //1 78 79 File file = new File("src"); 80 walkTree.filterFileType(file, true); //2 81 } 82}
输出:
1//1 2src\hello\Counter.java 3src\hello\FileTest.java 4src\housekeeping\Burrito.java 5 6 7//2 8Counter.java 9FileTest.java 10Burrito.java