• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package org.apache.commons.io.filefilter;
18 
19 import java.io.File;
20 import java.io.Serializable;
21 import java.nio.file.FileVisitResult;
22 import java.nio.file.Path;
23 import java.nio.file.attribute.BasicFileAttributes;
24 import java.util.Objects;
25 import java.util.function.Function;
26 import java.util.regex.Pattern;
27 
28 import org.apache.commons.io.IOCase;
29 
30 /**
31  * Filters files using supplied regular expression(s).
32  * <p>
33  * See java.util.regex.Pattern for regex matching rules.
34  * </p>
35  * <h2>Using Classic IO</h2>
36  * <p>
37  * e.g.
38  *
39  * <pre>
40  * File dir = FileUtils.current();
41  * FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
42  * File[] files = dir.listFiles(fileFilter);
43  * for (String file : files) {
44  *     System.out.println(file);
45  * }
46  * </pre>
47  *
48  * <h2>Using NIO</h2>
49  *
50  * <pre>
51  * final Path dir = PathUtils.current();
52  * final AccumulatorPathVisitor visitor = AccumulatorPathVisitor.withLongCounters(new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$"));
53  * //
54  * // Walk one dir
55  * Files.<b>walkFileTree</b>(dir, Collections.emptySet(), 1, visitor);
56  * System.out.println(visitor.getPathCounters());
57  * System.out.println(visitor.getFileList());
58  * //
59  * visitor.getPathCounters().reset();
60  * //
61  * // Walk dir tree
62  * Files.<b>walkFileTree</b>(dir, visitor);
63  * System.out.println(visitor.getPathCounters());
64  * System.out.println(visitor.getDirList());
65  * System.out.println(visitor.getFileList());
66  * </pre>
67  * <h2>Deprecating Serialization</h2>
68  * <p>
69  * <em>Serialization is deprecated and will be removed in 3.0.</em>
70  * </p>
71  *
72  * @since 1.4
73  */
74 public class RegexFileFilter extends AbstractFileFilter implements Serializable {
75 
76     private static final long serialVersionUID = 4269646126155225062L;
77 
78     /**
79      * Compiles the given pattern source.
80      *
81      * @param pattern the source pattern.
82      * @param flags the compilation flags.
83      * @return a new Pattern.
84      */
compile(final String pattern, final int flags)85     private static Pattern compile(final String pattern, final int flags) {
86         Objects.requireNonNull(pattern, "pattern");
87         return Pattern.compile(pattern, flags);
88     }
89 
90     /**
91      * Converts IOCase to Pattern compilation flags.
92      *
93      * @param ioCase case-sensitivity.
94      * @return Pattern compilation flags.
95      */
toFlags(final IOCase ioCase)96     private static int toFlags(final IOCase ioCase) {
97         return IOCase.isCaseSensitive(ioCase) ? 0 : Pattern.CASE_INSENSITIVE;
98     }
99 
100     /** The regular expression pattern that will be used to match file names. */
101     private final Pattern pattern;
102 
103     /** How convert a path to a string. */
104     private final Function<Path, String> pathToString;
105 
106     /**
107      * Constructs a new regular expression filter for a compiled regular expression
108      *
109      * @param pattern regular expression to match.
110      * @throws NullPointerException if the pattern is null.
111      */
112     @SuppressWarnings("unchecked")
RegexFileFilter(final Pattern pattern)113     public RegexFileFilter(final Pattern pattern) {
114         this(pattern, (Function<Path, String> & Serializable) p -> p.getFileName().toString());
115     }
116 
117     /**
118      * Constructs a new regular expression filter for a compiled regular expression
119      *
120      * @param pattern regular expression to match.
121      * @param pathToString How convert a path to a string.
122      * @throws NullPointerException if the pattern is null.
123      * @since 2.10.0
124      */
RegexFileFilter(final Pattern pattern, final Function<Path, String> pathToString)125     public RegexFileFilter(final Pattern pattern, final Function<Path, String> pathToString) {
126         Objects.requireNonNull(pattern, "pattern");
127         this.pattern = pattern;
128         this.pathToString = pathToString;
129     }
130 
131     /**
132      * Constructs a new regular expression filter.
133      *
134      * @param pattern regular string expression to match
135      * @throws NullPointerException if the pattern is null
136      */
RegexFileFilter(final String pattern)137     public RegexFileFilter(final String pattern) {
138         this(pattern, 0);
139     }
140 
141     /**
142      * Constructs a new regular expression filter with the specified flags.
143      *
144      * @param pattern regular string expression to match
145      * @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE}
146      * @throws IllegalArgumentException if the pattern is null
147      */
RegexFileFilter(final String pattern, final int flags)148     public RegexFileFilter(final String pattern, final int flags) {
149         this(compile(pattern, flags));
150     }
151 
152     /**
153      * Constructs a new regular expression filter with the specified flags case sensitivity.
154      *
155      * @param pattern regular string expression to match
156      * @param ioCase how to handle case sensitivity, null means case-sensitive
157      * @throws IllegalArgumentException if the pattern is null
158      */
RegexFileFilter(final String pattern, final IOCase ioCase)159     public RegexFileFilter(final String pattern, final IOCase ioCase) {
160         this(compile(pattern, toFlags(ioCase)));
161     }
162 
163     /**
164      * Checks to see if the file name matches one of the regular expressions.
165      *
166      * @param dir the file directory (ignored)
167      * @param name the file name
168      * @return true if the file name matches one of the regular expressions
169      */
170     @Override
accept(final File dir, final String name)171     public boolean accept(final File dir, final String name) {
172         return pattern.matcher(name).matches();
173     }
174 
175     /**
176      * Checks to see if the file name matches one of the regular expressions.
177      *
178      * @param path the path
179      * @param attributes the path attributes
180      * @return true if the file name matches one of the regular expressions
181      */
182     @Override
accept(final Path path, final BasicFileAttributes attributes)183     public FileVisitResult accept(final Path path, final BasicFileAttributes attributes) {
184         return toFileVisitResult(pattern.matcher(pathToString.apply(path)).matches());
185     }
186 
187     /**
188      * Returns a debug string.
189      *
190      * @since 2.10.0
191      */
192     @Override
toString()193     public String toString() {
194         return "RegexFileFilter [pattern=" + pattern + "]";
195     }
196 
197 }
198