1 package au.gov.amsa.util;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.Comparator;
7 import java.util.List;
8 import java.util.regex.Pattern;
9
10 public final class Files {
11
12 private static Comparator<File> FILE_COMPARATOR = (a, b) -> a.getAbsolutePath().compareTo(
13 b.getAbsolutePath());
14
15 public static List<File> find(File file, final Pattern pattern) {
16 return find(file, pattern, true);
17 }
18
19 public static List<File> find(File file, final Pattern pattern, boolean sort) {
20 if (!file.exists())
21 return Collections.emptyList();
22 else {
23 if (!file.isDirectory() && pattern.matcher(file.getName()).matches())
24 return Collections.singletonList(file);
25 else if (file.isDirectory()) {
26 List<File> list = new ArrayList<File>();
27 File[] files = file.listFiles();
28 if (files != null)
29 for (File f : file.listFiles()) {
30 if (!f.getName().startsWith(".")) {
31 if (f.isFile() && pattern.matcher(f.getName()).matches())
32 list.add(f);
33 else
34 list.addAll(find(f, pattern, sort));
35 }
36 }
37 Collections.sort(list, FILE_COMPARATOR);
38 return list;
39 } else
40 return Collections.emptyList();
41 }
42 }
43 }