改变 WatchService 的状态

Change state of WatchService

我正在编写一个应用程序,它将扫描一个目录以查找新添加的文件,然后使用 WatchService 对它们进行一些处理。这部分按预期工作。现在,我需要编写代码来处理在服务启动之前添加到目录中的文件。

天真的方法是在向 WatchService 注册路径之前简单地获取文件夹中的文件列表;不过,我担心这可能会在处理预先存在的文件和监视新事件之间留下差距,我可能会错过传入的文件。最安全的选择是开始监视事件,但不处理它们,直到我处理完已经存在的文件。

有什么方法可以手动将 WatchKey 的状态更改为 'signalled'?这将实现我的目标,但我在 WatchService 的文档中没有看到执行此操作的方法。

The naive approach would be to simply get a list of files in the folder before registering the path with the WatchService; I have concerns, though, that this may leave a gap between processing the pre-existing files and watching for new events, where I might miss incoming files. The safest option would be to start Watching for events, but not process them, until I've dealt with the files already present.

这里有一个解决问题的方法:

同时启动 watch-serviceget-files-list-from-folder-process

这两个进程都将文件(文件路径)放入线程安全队列集合中 - 首先 - 允许后进先出(LIFO)或先进先出(FIFO)处理。可以根据需要考虑java.util.concurrent.ConcurrentLinkedDequeLinkedBlockingDequeConcurrentLinkedQueueLinkedBlockingQueue。这样一来,所有文件都会一个接一个地处理 - 无论它是来自 get-files-list-from-folder-process 还是 watch-service。

但是,需要进行检查以避免重复文件处理,以确保没有文件被两次添加到队列中。这仅在申请开始时需要。实际文件处理程序本身可以跟踪在另一个集合中处理的文件 - 可用于检查文件是否已被处理。