View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.io.file;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertNotEquals;
23  
24  import java.nio.file.DirectoryStream;
25  import java.nio.file.Files;
26  import java.nio.file.Path;
27  import java.util.Iterator;
28  
29  import org.apache.commons.io.filefilter.NameFileFilter;
30  import org.junit.jupiter.api.Test;
31  
32  /**
33   * Tests {@link DirectoryStreamFilter}.
34   */
35  public class DirectoryStreamFilterTest {
36  
37      private static final String PATH_FIXTURE = "NOTICE.txt";
38  
39      @Test
40      public void testFilterByName() throws Exception {
41          final PathFilter pathFilter = new NameFileFilter(PATH_FIXTURE);
42          final DirectoryStreamFilter streamFilter = new DirectoryStreamFilter(pathFilter);
43          assertEquals(pathFilter, streamFilter.getPathFilter());
44          try (DirectoryStream<Path> stream = Files.newDirectoryStream(PathUtils.current(), streamFilter)) {
45              final Iterator<Path> iterator = stream.iterator();
46              final Path path = iterator.next();
47              assertEquals(PATH_FIXTURE, PathUtils.getFileNameString(path));
48              assertFalse(iterator.hasNext());
49          }
50      }
51  
52      @Test
53      public void testFilterByNameNot() throws Exception {
54          final PathFilter pathFilter = new NameFileFilter(PATH_FIXTURE).negate();
55          final DirectoryStreamFilter streamFilter = new DirectoryStreamFilter(pathFilter);
56          assertEquals(pathFilter, streamFilter.getPathFilter());
57          try (DirectoryStream<Path> stream = Files.newDirectoryStream(PathUtils.current(), streamFilter)) {
58              stream.forEach(path -> assertNotEquals(PATH_FIXTURE, PathUtils.getFileNameString(path)));
59          }
60      }
61  
62  }