简体   繁体   English

无法使用 PathMatcher 和正则表达式获取文件列表

[英]Can't get list of files using PathMatcher and regex

I'm using PathMatcher and SimpleFileVisitor to iterate over directory and find all the files that start only with a certain prefix.我正在使用 PathMatcher 和 SimpleFileVisitor 遍历目录并查找仅以特定前缀开头的所有文件。 However, I can't get any files although there are some files that match my preference.但是,尽管有一些文件符合我的喜好,但我无法获得任何文件。

Example of file required:所需文件示例:

Prefix_some_text.csv

Here is the Main code that invokes the call for SimpleFileVisitor class, and it uses regex pattern with the prefix and suppose to find all files starting with the certain pattern:下面是调用 SimpleFileVisitor class 的主要代码,它使用带前缀的正则表达式模式,并假设查找以特定模式开头的所有文件:

String directoryAsString = "C:/Users";
String pattern = "Prefix";
SearchFileByWildcard sfbw = new SearchFileByWildcard();
        try {
            List<String> actual = sfbw.searchWithWc(Paths.get(directoryAsString),pattern);
        } catch (IOException e) {
            e.printStackTrace();
        }

The implementation of SearchFileByWildcard class that uses SimpleFileVisitor:使用 SimpleFileVisitor 的 SearchFileByWildcard class 的实现:

static class SearchFileByWildcard {
    List<String> matchesList = new ArrayList<String>();
    List<String> searchWithWc(Path rootDir, String pattern) throws IOException {
        matchesList.clear();
        FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) throws IOException {
                FileSystem fs = FileSystems.getDefault();
                PathMatcher matcher = fs.getPathMatcher("regex:" + pattern);
                Path name = file.getFileName(); //takes the filename from the full path
                if (matcher.matches(name)) {
                    matchesList.add(name.toString());
                }
                return FileVisitResult.CONTINUE;
            }
        };
        Files.walkFileTree(rootDir, matcherVisitor);
        return matchesList;
    }
}

I'm debating whether to use glob instead of regex?我在争论是否使用 glob 而不是 regex? Or maybe something with my regex is flawed.或者我的正则表达式可能有问题。

It seems like the pattern is wrong.好像模式不对。 It matches only files named "Prefix".它只匹配名为“Prefix”的文件。 Try to change it in String pattern = "Prefix.*";尝试在String pattern = "Prefix.*";中更改它. .

Otherwise you can scan for files which name starts by the string "Prefix".否则,您可以扫描名称以字符串“Prefix”开头的文件。

String name = file.getFileName().toString();
if (name.startsWith(pattern)) {
    matchesList.add(name);
}

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

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