How to find files that match a wildcard string in Java?

前端 未结 16 921
慢半拍i
慢半拍i 2020-11-22 10:52

This should be really simple. If I have a String like this:

../Test?/sample*.txt

then what is a generally-accepted way to get a list of fil

相关标签:
16条回答
  • 2020-11-22 11:17

    Here are examples of listing files by pattern powered by Java 7 nio globbing and Java 8 lambdas:

        try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
                Paths.get(".."), "Test?/sample*.txt")) {
            dirStream.forEach(path -> System.out.println(path));
        }
    

    or

        PathMatcher pathMatcher = FileSystems.getDefault()
            .getPathMatcher("regex:Test./sample\\w+\\.txt");
        try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
                new File("..").toPath(), pathMatcher::matches)) {
            dirStream.forEach(path -> System.out.println(path));
        }
    
    0 讨论(0)
  • 2020-11-22 11:19

    Since Java 8 you can use Files#find method directly from java.nio.file.

    public static Stream<Path> find(Path start,
                                    int maxDepth,
                                    BiPredicate<Path, BasicFileAttributes> matcher,
                                    FileVisitOption... options)
    

    Example usage

    Files.find(startingPath,
               Integer.MAX_VALUE,
               (path, basicFileAttributes) -> path.toFile().getName().matches(".*.pom")
    );
    
    0 讨论(0)
  • 2020-11-22 11:19

    Implement the JDK FileVisitor interface. Here is an example http://wilddiary.com/list-files-matching-a-naming-pattern-java/

    0 讨论(0)
  • 2020-11-22 11:20

    Try FileUtils from Apache commons-io (listFiles and iterateFiles methods):

    File dir = new File(".");
    FileFilter fileFilter = new WildcardFileFilter("sample*.java");
    File[] files = dir.listFiles(fileFilter);
    for (int i = 0; i < files.length; i++) {
       System.out.println(files[i]);
    }
    

    To solve your issue with the TestX folders, I would first iterate through the list of folders:

    File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
    for (int i=0; i<dirs.length; i++) {
       File dir = dirs[i];
       if (dir.isDirectory()) {
           File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
       }
    }
    

    Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.

    0 讨论(0)
提交回复
热议问题