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