|
3 | 3 | import io.github.benas.unixstream.components.WordCount;
|
4 | 4 |
|
5 | 5 | import java.io.*;
|
6 |
| -import java.nio.file.Paths; |
| 6 | +import java.nio.file.*; |
7 | 7 | import java.util.Arrays;
|
8 | 8 | import java.util.Comparator;
|
9 | 9 | import java.util.Date;
|
10 | 10 | import java.util.Objects;
|
11 | 11 | import java.util.function.Predicate;
|
12 | 12 | import java.util.stream.Stream;
|
13 | 13 |
|
| 14 | +import static java.nio.file.Files.isDirectory; |
14 | 15 | import static java.nio.file.Files.lines;
|
| 16 | +import static java.nio.file.Files.walk; |
15 | 17 |
|
16 | 18 | /**
|
17 | 19 | * This interface is the main entry point to use UnixStream.
|
@@ -129,6 +131,28 @@ static UnixStream<String> pwd() {
|
129 | 131 | return new UnixStreamImpl<>(Stream.of(Paths.get("").toFile().getAbsolutePath()));
|
130 | 132 | }
|
131 | 133 |
|
| 134 | + |
| 135 | + /** |
| 136 | + * Find files by name (recursively) in a given directory. |
| 137 | + * |
| 138 | + * @param directory the root directory |
| 139 | + * @param pattern the file name pattern with <a href="https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob">glob syntax</a>. |
| 140 | + * @return a new UnixStream with found files |
| 141 | + */ |
| 142 | + static UnixStream<Path> find(final Path directory, final String pattern) { |
| 143 | + Objects.requireNonNull(directory, "The root directory must not be null"); |
| 144 | + Objects.requireNonNull(pattern, "The file pattern must not be null"); |
| 145 | + PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); |
| 146 | + try { |
| 147 | + return new UnixStreamImpl<>(walk(directory) |
| 148 | + .filter(path -> !isDirectory(path)) |
| 149 | + .filter(path -> pathMatcher.matches(path.getFileName()))); |
| 150 | + |
| 151 | + } catch (IOException e) { |
| 152 | + throw new RuntimeException("Unable to find files in directory " + directory); |
| 153 | + } |
| 154 | + } |
| 155 | + |
132 | 156 | /**
|
133 | 157 | * Create a new UnixStream fro the given stream.
|
134 | 158 | *
|
|
0 commit comments