簡體   English   中英

使用Java 8 Parallel Stream在並行讀取多個文件時排除某些文件

[英]Exclude some files while reading multiple Files in Parallel using Java 8 Parallel Stream

我正在從文件夾中讀取多個文件(大約5mb的1000個文件)。 下面的代碼可以正常讀取,加載和存儲文件的內容。

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”&& flag為true)

在此先感謝您的任何建議。

Files.walk()返回Stream<Path>因此您無需將其轉換為列表。 使用以下代碼並行使用並根據條件對其進行過濾。

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) {

}

我會使用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表示形式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM