java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java文件查找

基于Java IO API实现文件查找工具

作者:Cache技术分享

这篇文章主要为大家详细介绍了如何基于Java IO API实现文件查找Find工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

Java IO API - Java 文件查找工具

这是一个用 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();
    }
}

功能简介

这个程序会:

例如:

$ java Find . -name "*.java"

会打印当前目录及其子目录中所有以 .java 结尾的文件。

示例代码结构详解

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();
}

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);
    }
}

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()
过滤某些目录(如 .gitpreVisitDirectory() 中判断名称并返回 SKIP_SUBTREE
使用正则表达式匹配替换为 getPathMatcher("regex:" + pattern)
跟踪符号链接使用 EnumSet.of(FileVisitOption.FOLLOW_LINKS) 作为 walkFileTree() 参数
查找结果写入文件System.out.println(...) 替换为写入 BufferedWriter

小贴士:PathMatcher 注意事项

错误处理建议

结语

这个 Find 示例是理解 Java 文件遍历与模式匹配机制的绝佳入门材料。它涵盖了:

在实际项目中,结合该示例可构建自己的文件过滤工具、批量处理脚本或配置管理工具。

到此这篇关于基于Java IO API实现文件查找工具的文章就介绍到这了,更多相关Java文件查找内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文