问题描述
我们如何结合以下两个流逻辑:
public void filterRecord(File inputDirectory) throws IOException {
if (inputDirectory.exists() && !inputDirectory.isDirectory()) {
List<Path> pathStreams = Files.list(Paths.get(inputDirectory.getAbsolutePath()))
.filter(path -> path.toString().endsWith(".csv"))
.collect(Collectors.toList());
for (Path filePath : pathStreams) {
Files.lines(filePath)
.filter(line -> (line != null && !line.isEmpty()))
.filter(line -> "10".equals(line.substring(0,line.indexOf(",")).trim()))
.forEach(System.out::println);
}
}
}
在上面的代码中,两个流都参与其中,
- 第一个流使用目录路径对文件列表进行特定范围的过滤。
- 第二个流是从文件中过滤内容并在控制台上打印。
解决方法
public void fileStreamsFilter(Path inputDirectoryPath) throws IOException {
if (Files.exists(inputDirectoryPath) && Files.isDirectory(inputDirectoryPath)) {
Files.list(inputDirectoryPath).filter(path -> path.toString().endsWith(".csv"))
.flatMap(path -> {
try {
return Files.lines(path);
} catch (IOException ioException) {
log.error(ioException.getMessage(),ioException);
}
return null;
})
.filter(line -> (line != null && !line.isEmpty()))
.filter(line -> "10".equals(line.substring(0,line.indexOf(",")).trim()))
.forEach(log::info);
}
}