1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.rolling.helper;
15
16 import java.io.File;
17 import java.io.FilenameFilter;
18 import java.util.Arrays;
19 import java.util.Comparator;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22
23 public class FileFilterUtil {
24
25 public static void sortFileArrayByName(File[] fileArray) {
26 Arrays.sort(fileArray, new Comparator<File>() {
27 public int compare(File o1, File o2) {
28 String o1Name = o1.getName();
29 String o2Name = o2.getName();
30 return (o1Name.compareTo(o2Name));
31 }
32 });
33 }
34
35 public static void reverseSortFileArrayByName(File[] fileArray) {
36 Arrays.sort(fileArray, new Comparator<File>() {
37 public int compare(File o1, File o2) {
38 String o1Name = o1.getName();
39 String o2Name = o2.getName();
40 return (o2Name.compareTo(o1Name));
41 }
42 });
43 }
44
45 public static String afterLastSlash(String sregex) {
46 int i = sregex.lastIndexOf('/');
47 if (i == -1) {
48 return sregex;
49 } else {
50 return sregex.substring(i + 1);
51 }
52 }
53
54 static public boolean isEmptyDirectory(File dir) {
55 if (!dir.isDirectory()) {
56 throw new IllegalArgumentException("[" + dir + "] must be a directory");
57 }
58 String[] filesInDir = dir.list();
59 if (filesInDir == null || filesInDir.length == 0) {
60 return true;
61 } else {
62 return false;
63 }
64 }
65
66
67
68
69
70
71
72
73
74 public static File[] filesInFolderMatchingStemRegex(File file, final String stemRegex) {
75
76 if (file == null) {
77 return new File[0];
78 }
79 if (!file.exists() || !file.isDirectory()) {
80 return new File[0];
81 }
82
83
84 Pattern pattern = Pattern.compile(stemRegex);
85 return file.listFiles((dir, name) -> pattern.matcher(name).matches());
86 }
87
88 static public int findHighestCounter(File[] matchingFileArray, final String stemRegex) {
89 int max = Integer.MIN_VALUE;
90 for (File aFile : matchingFileArray) {
91 int aCounter = FileFilterUtil.extractCounter(aFile, stemRegex);
92 if (max < aCounter)
93 max = aCounter;
94 }
95 return max;
96 }
97
98 static public int extractCounter(File file, final String stemRegex) {
99 Pattern p = Pattern.compile(stemRegex);
100 String lastFileName = file.getName();
101
102 Matcher m = p.matcher(lastFileName);
103 if (!m.matches()) {
104 throw new IllegalStateException("The regex [" + stemRegex + "] should match [" + lastFileName + "]");
105 }
106 String counterAsStr = m.group(1);
107 return Integer.parseInt(counterAsStr);
108 }
109
110 public static String slashify(String in) {
111 return in.replace('\\', '/');
112 }
113
114 public static void removeEmptyParentDirectories(File file, int recursivityCount) {
115
116 if (recursivityCount >= 3) {
117 return;
118 }
119 File parent = file.getParentFile();
120 if (parent.isDirectory() && FileFilterUtil.isEmptyDirectory(parent)) {
121 parent.delete();
122 removeEmptyParentDirectories(parent, recursivityCount + 1);
123 }
124 }
125 }