我正在尝试创建一个观察者来查找对特定文件夹的更改。我创建了一个观察者并将它放在一个异步方法中,但是当我从服务中调用它时,应用程序由于观察者方法中的 while 循环而暂停。就像该方法没有在新线程中执行一样。
这是包含我要执行的方法的类;
@Service
public class FileWatcher {
@Async
public Future<Object> watch(Path path, DataParser parser) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
File file = new File(path.toString() + "/" + event.context());
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
parser.fileChanged(file);
}
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
parser.fileCreated(file);
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
parser.fileRemoved(file);
}
}
key.reset();
}
return null;
}
}
然后,我在服务的构造函数中调用它。
@Service
public class SPIService {
private final String DATAFOLDER = "/spi";
private Path dataPath;
public SPIService(@Value("${com.zf.trw.visualisation.data.path}") String dataPath) {
this.dataPath = Paths.get(dataPath + DATAFOLDER);
FileWatcher fileWatcher = new FileWatcher();
try {
fileWatcher.watch(this.dataPath, new SPIParser());
} catch (Exception e) {
e.printStackTrace();
}
}
}
为什么这不起作用?是因为我从服务的构造函数中调用方法吗?
斯蒂芬大帝
相关分类