我正在从文件夹中读取多个文件(1000 个大小约为 5 MB 的文件)。下面的代码可以很好地读取、加载和存储文件的内容。
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()
返回 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) {
}
关于java - 使用 Java 8 Parallel Stream 在并行读取多个文件时排除一些文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54372124/