[英]Return a map with file sizes using a lambda expression and a regular expression java
如何返回具有指定目錄中名稱與指定掩碼匹配的文件大小的映射。 DOS 掩碼可以包含特殊字符“*”和“?”。
我的代碼:
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()));
}
}
如果你知道,告訴我正確的正則表達式。 我做了這個表達式:“(?:(?:*)?(?:\\w+))|(?:(?:\\?)(?:\\w))”
所以為了結合 VGR 的優秀建議和你稍微調整的代碼,我們得到了這樣的東西:
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);
}
}
));
}
這里最丑陋的部分是在 lambda 中處理IOException
......
有了這個實現,可能會有問題?
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()));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.