1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| package com.muchlab.io;
import net.mindview.util.PPrint;
import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Spliterator; import java.util.function.Consumer; import java.util.regex.Pattern;
public class Directory { public static File[] local(File dir, final String regex){ return dir.listFiles(new FilenameFilter() { private Pattern pattern = Pattern.compile(regex); @Override public boolean accept(File dir, String name) { return pattern.matcher(new File(name).getName()).matches(); } }); } public static File[] local(String path, final String regex){ return local(new File(path), regex); } public static class TreeInfo implements Iterable<File>{ public List<File> files = new ArrayList<>(); public List<File> dirs = new ArrayList<>();
@Override public Iterator<File> iterator() { return files.iterator(); }
@Override public void forEach(Consumer<? super File> action) {
} void addAll(TreeInfo other){ files.addAll(other.files); dirs.addAll(other.dirs); }
@Override public String toString() { return "dirs: "+ PPrint.pformat(dirs)+"\n\nfiles: "+PPrint.pformat(files); }
public static TreeInfo walk(String start, String regex){ return recurseDirs(new File(start), regex); } public static TreeInfo walk(File start, String regex){ return recurseDirs(start, regex); } public static TreeInfo walk(File start){ return recurseDirs(start, ".*"); }
public static TreeInfo walk(String start){ return recurseDirs(new File(start), ".*"); }
private static TreeInfo recurseDirs(File startDir, String regex) { TreeInfo result = new TreeInfo(); for (File file : startDir.listFiles()) { if (file.isDirectory()){ result.dirs.add(file); result.addAll(recurseDirs(file, regex)); } if (file.getName().matches(regex)) result.files.add(file); } return result; }
public static void main(String[] args) {
System.out.println(walk(new File("D://CloudMusic"))); } } }
|