我想问你一个关于WatchService的问题.因此,当目录中出现我要重命名特定文件的代码.但是我想将WatchService的超时设置为2分钟(如果目录内没有任何反应).
但是从我的读物来看.有超时,但仅在启动监视目录之前处于睡眠状态.
因此,代码如下所示:
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)) {
consumer.accept(dirPath + fileName);
return;
}
}
key.reset();
}
}
catch (IOException | InterruptedException e) {}
还是有其他解决方法?
最佳答案
如果要在等待事件时超时,则需要使用