DirectoryStream Glob Pattern Listing
List directory entries through DirectoryStream glob patterns, sorting results yourself because entry order is unspecified by the JDK.
Code
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class LogCollector {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("logs-");
Files.writeString(dir.resolve("app.log"), "level=info");
Files.writeString(dir.resolve("db.log"), "level=warn");
Files.writeString(dir.resolve("notes.txt"), "rotate at 10MB");
Files.writeString(dir.resolve("heap.png"), "binary");
// glob 语法只筛 *.log;目录项顺序不保证,收集后排序输出
List<String> logs = new ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.log")) {
for (Path entry : entries) {
logs.add(entry.getFileName().toString());
}
}
logs.sort(String::compareTo);
System.out.println("logs: " + logs);
// 花括号多 pattern:一次匹配两种扩展名
List<String> rotate = new ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.{log,txt}")) {
for (Path entry : entries) {
rotate.add(entry.getFileName().toString());
}
}
rotate.sort(String::compareTo);
System.out.println("rotate: " + rotate);
// 不带 pattern:列出全部条目,顺手清理临时目录
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir)) {
for (Path entry : entries) {
Files.deleteIfExists(entry);
}
}
Files.deleteIfExists(dir);
}
}What the code does
DirectoryStream Glob Pattern Listing keeps everything in the class LogCollector.
Repetition is confined to for (Path entry : entries) — the rest of the file is straight-line. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Applying it
Look for the logs:, rotate: prefixes when the file runs; they tie each line to its step.
Statements that matter
rotate.sort(String::compareTo);
logs.sort(String::compareTo);
Interactive Tools for This Topic
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does DirectoryStream Glob Pattern Listing print when run?
- Execute the whole file; each printed line is prefixed with a label like `logs:`, `rotate:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.