    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.io.file;
    019
    020import java.io.IOException;
    021import java.nio.file.DirectoryStream;
    022import java.nio.file.FileVisitResult;
    023import java.nio.file.Path;
    024import java.util.Objects;
    025
    026/**
    027 * A {@link java.nio.file.DirectoryStream.Filter DirectoryStream.Filter} that delegates to a {@link PathFilter}.
    028 * <p>
    029 * You pass this filter to {@link java.nio.file.Files#newDirectoryStream(Path, DirectoryStream.Filter)
    030 * Files#newDirectoryStream(Path, DirectoryStream.Filter)}.
    031 * </p>
    032 *
    033 * @since 2.9.0
    034 */
    035public class DirectoryStreamFilter implements DirectoryStream.Filter<Path> {
    036
    037    private final PathFilter pathFilter;
    038
    039    /**
    040     * Constructs a new instance for the given path filter.
    041     *
    042     * @param pathFilter How to filter paths.
    043     */
    044    public DirectoryStreamFilter(final PathFilter pathFilter) {
    045        // TODO Instead of NPE, we could map null to FalseFileFilter.
    046        this.pathFilter = Objects.requireNonNull(pathFilter, "pathFilter");
    047    }
    048
    049    @Override
    050    public boolean accept(final Path path) throws IOException {
    051        return pathFilter.accept(path, PathUtils.readBasicFileAttributes(path, PathUtils.EMPTY_LINK_OPTION_ARRAY)) == FileVisitResult.CONTINUE;
    052    }
    053
    054    /**
    055     * Gets the path filter.
    056     *
    057     * @return the path filter.
    058     */
    059    public PathFilter getPathFilter() {
    060        return pathFilter;
    061    }
    062
    063}