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

前端 未结 16 1146
慢半拍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 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 dirStream = Files.newDirectoryStream(
                new File("..").toPath(), pathMatcher::matches)) {
            dirStream.forEach(path -> System.out.println(path));
        }
    

提交回复
热议问题