001    /*
002     * Copyright (C) 2006 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.io;
018    
019    import com.google.common.annotations.Beta;
020    import com.google.common.base.Preconditions;
021    
022    import java.io.File;
023    import java.io.FilenameFilter;
024    import java.util.regex.Pattern;
025    import java.util.regex.PatternSyntaxException;
026    
027    import javax.annotation.Nullable;
028    
029    /**
030     * File name filter that only accepts files matching a regular expression. This class is thread-safe
031     * and immutable.
032     *
033     * @author Apple Chow
034     * @since 1.0
035     */
036    @Beta
037    public final class PatternFilenameFilter implements FilenameFilter {
038    
039      private final Pattern pattern;
040    
041      /**
042       * Constructs a pattern file name filter object.
043       * @param patternStr the pattern string on which to filter file names
044       *
045       * @throws PatternSyntaxException if pattern compilation fails (runtime)
046       */
047      public PatternFilenameFilter(String patternStr) {
048        this(Pattern.compile(patternStr));
049      }
050    
051      /**
052       * Constructs a pattern file name filter object.
053       * @param pattern the pattern on which to filter file names
054       */
055      public PatternFilenameFilter(Pattern pattern) {
056        this.pattern = Preconditions.checkNotNull(pattern);
057      }
058    
059      @Override public boolean accept(@Nullable File dir, String fileName) {
060        return pattern.matcher(fileName).matches();
061      }
062    }