【问题标题】:How to get all files from directory and sub directory with a given pattern如何从给定模式的目录和子目录中获取所有文件
【发布时间】:2014-08-22 16:41:33
【问题描述】:

我有一个包含子目录的目录,每个目录都有一个名为 *.properties

我想用java搜索这些文件

谢谢

【问题讨论】:

标签: java file properties path dir


【解决方案1】:

见java教程Walking the File Tree

您是否需要创建一个将递归访问文件树中所有文件的应用程序?也许您需要删除树中的每个 .class 文件,或者查找去年未访问过的每个文件。您可以使用 FileVisitor 界面执行此操作。

具体参见Finding Files 示例:

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

【讨论】:

    【解决方案2】:

    你可以递归调用这个方法

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

    您也可以使用 Java 7 Files.walkTree 方法和过滤器,如 here 所述。

    【讨论】:

      【解决方案3】:

      除了其他答案:

      番石榴(自 v15 起):

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

      公共 IO:

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

      Java 7:

      Files.walkFileTree(rootDir, fileVisitor);
      

      【讨论】:

        猜你喜欢
        • 2019-08-14
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多