我有通过Java中的WatchService监控目录的代码。但目前我使用循环,但我想将其更改为streams。
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(dirPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
String fileName = event.context().toString();
if (isPdfFile(fileName)) {
runOnOption.get(option).accept(dirFilePath);
return;
}
}
key.reset();
}
}
catch (IOException | InterruptedException e) {}
}方法isPdfFile检查文件是否为pdf,如果是,它将重命名并创建用于重命名的日志文件。所以我能做的是:
key.pollEvents()
.stream()
.filter(e -> isEdxFile(e.context().toString()))
.forEach( e -> runOnOption.get(option).accept(dirPath+e.context().toString()));但是我遗漏的是while循环和return from loop,当它找到带有pdf扩展名的文件时。
发布于 2019-02-06 21:52:30
你可能要找的是
.findFirst() // first element with such a filter condition
.ifPresent(e -> runOnOption.get(option).accept(dirPath+e.context().toString()));在执行使用者逻辑后,一旦找到这样的元素就返回。
https://stackoverflow.com/questions/54554828
复制相似问题