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 org.checkerframework.checker.nullness.qual.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 * @throws PatternSyntaxException if pattern compilation fails (runtime) 044 */ 045 public PatternFilenameFilter(String patternStr) { 046 this(Pattern.compile(patternStr)); 047 } 048 049 /** 050 * Constructs a pattern file name filter object. 051 * 052 * @param pattern the pattern on which to filter file names 053 */ 054 public PatternFilenameFilter(Pattern pattern) { 055 this.pattern = Preconditions.checkNotNull(pattern); 056 } 057 058 @Override 059 public boolean accept(@Nullable File dir, String fileName) { 060 return pattern.matcher(fileName).matches(); 061 } 062}