Home » Java » regex – Return a map with file sizes using a lambda expression and a regular expression java-Exceptionshub

regex – Return a map with file sizes using a lambda expression and a regular expression java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

How to return a map with the size of files in the specified directory whose names match the specified mask. A DOS mask can contain special characters ‘ * ‘ and ‘?’.

My code:

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    return Files.walk(dir)
            .filter(Files::isRegularFile)
            .filter( x -> x.toFile().getName().equals(mask))
            How to make a filter by mask and regular expression correctly? Where to insert "regex"?
            .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
}
}

And if you know, tell me the correct regular expression. I made this expression: “(?:(?:*)?(?:\w+))|(?:(?:\?)(?:\w))”

How to&Answers:

So to combine VGR’s excellent suggestion and your slightly tweaked code we’re getting something like that:

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:" + mask);
    return Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)
            .filter(Files::isRegularFile)
            .filter(path -> pathMatcher.matches(path.getFileName()))
            .collect(Collectors.toMap(
                    Path::getFileName,
                    path -> {
                        try {
                            return Files.size(path);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }
            ));
}

The ugliest part here is handling IOException inside lambda…

Answer:

With this implementation, there may be problems?

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    final PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:**/*" + mask + "*");

    try (final Stream<Path> stream = Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)) {
        return stream.filter(pathMatcher::matches)
                .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
    }
}