[英]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.