Iterating over a directory and filter by file extension
suggest changeThe matcher tests the whole file name. The \\. requires a dot before the extension, so a name such as reportjpg does not match. This stream is not recursive.
public void iterateAndFilter() throws IOException {
Path dir = Paths.get("C:/foo/bar");
PathMatcher imageFileMatcher =
FileSystems.getDefault().getPathMatcher(
"regex:.*\\.(?i:jpg|jpeg|png|gif|bmp|jpe|jfif)");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,
entry -> imageFileMatcher.matches(entry.getFileName()))) {
for (Path path : stream) {
System.out.println(path.getFileName());
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents