【问题标题】:Exclude some files while reading multiple Files in Parallel using Java 8 Parallel Stream使用 Java 8 并行流并行读取多个文件时排除一些文件
【发布时间】:2019-06-19 16:37:20
【问题描述】:

我正在从文件夹中读取多个文件(1000 个大小约为 5mb 的文件)。下面的代码可以很好地读取、加载和存储文件的内容。

public void readAllFiles(String path) {

    try (Stream<Path> paths = Files.walk(Paths.get(path)).collect(toList()).parallelStream()) {
        paths.forEach(filePath -> {

            if (filePath.toFile().exists()) {
                String fileName = filePath.getFileName().toString();
                try {
                        List<String> loadedFile = readContent(filePath);
                        storeFiles(fileName, filePath, loadedFile);
                } catch (Exception e) {
                    LOGGER.info("ERROR WHILE READING THE CONTENT OF FILE");
                    LOGGER.error(e.getMessage());
                }
            }
        });
    } catch (IOException e) {
        LOGGER.info("ERROR WHILE READING THE FILES IN PARALLEL");
        LOGGER.error(e.getMessage());
    }
}

我的问题是在读取文件时我想排除一些文件,例如排除文件读取,例如条件满足(文件名包含“ABC”&&标志为真)

提前感谢您的任何建议。

【问题讨论】:

  • 试试这个Files.walk(Paths.get(path)).parallel() .filter(filePath-&gt;someConditions))...

标签: java multithreading java-8 parallel-processing java-stream


【解决方案1】:

Files.walk() 返回Stream&lt;Path&gt;,因此您无需将其转换为列表。 使用以下代码并行使用并过滤它 根据条件。

try (Stream<Path> paths = Files.walk(Paths.get(path)).parallel()
    .filter(filePath->filePath.getFileName().toString().contains("ABC"))) {
        paths.forEach(filePath -> {
            //other staff...
        });
    } catch (IOException e) {

}

【讨论】:

    【解决方案2】:

    我会使用filter 函数重写它:

    paths.filter(e -> e.toFile().exists())              //Make sure each file exists
         .map(path -> path.getFileName().toString())    //Map it to its fileName
         .filter(file -> !file.contains("someString"))  //Filter 
         .forEach(fileName -> {                         //Rest of logic
                try { 
                        List<String> loadedFile = readContent(filePath);
                        storeFiles(fileName, filePath, loadedFile);
                } catch (Exception e) {
                    LOGGER.info("ERROR WHILE READING THE CONTENT OF FILE");
                    LOGGER.error(e.getMessage());
                }            
        });
    

    在您执行 forEach 之前,这将映射到 String 的表示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 2017-04-25
      • 2012-02-16
      • 2019-02-10
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多