Java:如何进一步简化文件的Java 8流逻辑

问题描述

我们如何结合以下两个流逻辑:

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);
            }
        }
    }

在上面的代码中,两个流都参与其中,

  1. 第一个流使用目录路径对文件列表进行特定范围的过滤。
  2. 第二个流是从文件中过滤内容并在控制台上打印。

解决方法

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);
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...