383. Java IO API - Java 文件查找工具:Find 示例完整解析
这是一个用 Java 编写的简单文件查找工具,它模仿了 Linux 中的 find 命令,允许你通过 glob 模式查找符合特定命名规则的文件或目录。
/**
* Sample code that finds files that match the specified glob pattern.
* For more information on what constitutes a glob pattern, see
* https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob
*
* The file or directories that match the pattern are printed to
* standard out. The number of matches is also printed.
*
* When executing this application, you must put the glob pattern
* in quotes, so the shell will not expand any wild cards:
* java Find . -name "*.java"
*/
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import static java.nio.file.FileVisitOption.*;
import java.util.*;
public class Find {
public static class Finder
extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern) {
matcher = FileSystems.getDefault()
.getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
}
}
// Prints the total number of
// matches to standard out.
void done() {
System.out.println("Matched: "
+ numMatches);
}
// Invoke the pattern matching
// method on each file.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
find(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
static void usage() {
System.err.println("java Find <path>" +
" -name \"<glob_pattern>\"");
System.exit(-1);
}
public static void main(String[] args)
throws IOException {
if (args.length < 3 || !args[1].equals("-name"))
usage();
Path startingDir = Paths.get(args[0]);
String pattern = args[2];
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
}
📝 功能简介
这个程序会:
- 遍历指定目录及其子目录;
- 使用 glob 模式匹配文件或目录名;
- 输出所有匹配项的路径;
- 输出匹配总数。
例如:
$ java Find . -name "*.java"
会打印当前目录及其子目录中所有以 .java 结尾的文件。
✅ 示例代码结构详解
1️⃣ main() 方法:入口程序
public static void main(String[] args) throws IOException {
if (args.length < 3 || !args[1].equals("-name"))
usage();
Path startingDir = Paths.get(args[0]);
String pattern = args[2];
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
- 接收命令行参数:路径 +
-name+ glob 模式。 - 使用
Files.walkFileTree()遍历文件树。 - 调用 Finder 匹配并输出结果。
2️⃣ Finder 类:自定义文件访问器
public static class Finder extends SimpleFileVisitor<Path> {
继承 SimpleFileVisitor<Path>,重写几个核心方法来自定义行为:
🧩 构造方法:初始化 glob 匹配器
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
示例:"*.java" ➜ 匹配所有 Java 源文件。
🔍 find() 方法:核心匹配逻辑
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
}
}
- 使用
matcher.matches(...)判断文件是否匹配; - 统计匹配个数;
- 输出匹配路径。
📂 preVisitDirectory():遍历目录前的匹配逻辑
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
find(dir); // 匹配目录名
return CONTINUE;
}
不仅可以匹配文件,也能匹配目录名称。
📄 visitFile():遍历文件时的匹配逻辑
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
对每一个文件调用 find() 方法。
⚠️ visitFileFailed():错误处理
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println(exc);
return CONTINUE;
}
如果文件访问失败(如权限问题),打印错误但不终止遍历。
📊 done():打印统计结果
void done() {
System.out.println("Matched: " + numMatches);
}
在遍历完成后显示总共找到多少个匹配项。
🧪 运行示例
$ java Find . -name "*.html"
输出:
./index.html
./docs/help.html
Matched: 2
🧠 扩展思路与练习建议
| 扩展功能 | 实现方法 |
|---|---|
| 仅查找文件,不查找目录 | 在 visitFile() 中匹配,preVisitDirectory() 不调用 find() |
过滤某些目录(如 .git) | 在 preVisitDirectory() 中判断名称并返回 SKIP_SUBTREE |
| 使用正则表达式匹配 | 替换为 getPathMatcher("regex:" + pattern) |
| 跟踪符号链接 | 使用 EnumSet.of(FileVisitOption.FOLLOW_LINKS) 作为 walkFileTree() 参数 |
| 查找结果写入文件 | 将 System.out.println(...) 替换为写入 BufferedWriter |
🔔 小贴士:PathMatcher 注意事项
- 仅文件名匹配:要记得用
file.getFileName()而不是整个Path,否则路径中目录部分也会被匹配。 - 通配符需要加引号:如
"*.java",否则 shell 会提前展开通配符。
🧯 错误处理建议
- 可以改进
visitFileFailed()的行为,比如记录失败日志或重试。 - 使用
try-catch包装walkFileTree(),处理整体异常。
✅ 结语
这个 Find 示例是理解 Java 文件遍历与模式匹配机制的绝佳入门材料。它涵盖了:
walkFileTree的用法;- 文件访问器的重写方式;
PathMatcher的实际应用;- glob 模式的基础。
在实际项目中,结合该示例可构建自己的文件过滤工具、批量处理脚本或配置管理工具。