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    /**
028     * File name filter that only accepts files matching a regular expression.
029     *
030     * @author Apple Chow
031     * @since 1
032     */
033    @Beta
034    public final class PatternFilenameFilter implements FilenameFilter {
035    
036      private final Pattern pattern;
037    
038      /**
039       * Constructs a pattern file name filter object.
040       * @param patternStr the pattern string on which to filter file names
041       *
042       * @throws PatternSyntaxException if pattern compilation fails (runtime)
043       */
044      public PatternFilenameFilter(String patternStr) {
045        this(Pattern.compile(patternStr));
046      }
047    
048      /**
049       * Constructs a pattern file name filter object.
050       * @param pattern the pattern on which to filter file names
051       */
052      public PatternFilenameFilter(Pattern pattern) {
053        this.pattern = Preconditions.checkNotNull(pattern);
054      }
055    
056      @Override public boolean accept(File dir, String fileName) {
057        return pattern.matcher(fileName).matches();
058      }
059    }