简体   繁体   English

如何从给定模式的目录和子目录中获取所有文件

[英]How to get all files from directory and sub directory with a given pattern

I have a directory containing sub directories each one of this directories has a file called *.properties 我有一个包含子目录的目录,每个目录都有一个名为* .properties的文件

I want to search for these files with java 我想用Java搜索这些文件

Thanks 谢谢

You can recursively call this method 您可以递归调用此方法

File dir = new File("C:/");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
    return name.endsWith(".properties");
    }
});

Alternately you use Java 7 Files.walkTree method and filter as described here . 或者,您使用Java 7 Files.walkTree方法并按此处所述进行过滤。

See the java tutorial Walking the File Tree : 请参阅Java教程“ 遍历文件树”

Do you need to create an application that will recursively visit all the files in a file tree? 您是否需要创建一个可以递归访问文件树中所有文件的应用程序? Perhaps you need to delete every .class file in a tree, or find every file that hasn't been accessed in the last year. 也许您需要删除树中的每个.class文件,或者查找去年未访问的每个文件。 You can do so with the FileVisitor interface. 您可以使用FileVisitor界面执行此操作。

In particular see the Finding Files example: 特别是请参阅“ 查找文件”示例:

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.*;

/**
 * Sample code that finds files that
 * match the specified glob pattern.
 * For more information on what
 * constitutes a glob pattern, see
 * http://docs.oracle.com/javase/javatutorials/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"
 */

public class Find {

    /**
     * A {@code FileVisitor} that finds
     * all files that match the
     * specified pattern.
     */
    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();
    }
}

In addition to other answers: 除了其他答案:

Guava (since v15): 番石榴(v15起):

for (File f : Files.fileTreeTraverser().preOrderTraversal(rootDir)) {
    // filter and process
}

Commons IO: 共用IO:

for (File f : FileUtils.listFiles(rootDir, fileFilter, dirFilter)) {
    // process
}

Java 7: Java 7:

Files.walkFileTree(rootDir, fileVisitor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM