我正在寻找一种在 Java 1.8 中修改文件(如修改和/或更改文件)之前让线程 hibernate 的方法。基本上,这个线程必须读取文件的内容,警惕任何变化,但不能仅仅为了读取文件、等待、再次读取、等待等而吸收一个核心。
理想情况下,线程会阻塞,就像并发阻塞队列将线程置于 hibernate 状态,直到有东西要从队列中移除。
有什么想法吗?
最佳答案
您可以使用 NIO WatchService
:
A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
要使用它你需要:
// 1 create the watchService
WatchService watchService = FileSystems.getDefault().newWatchService();
// 2 get a reference to the directory to be watched for changes
String watchedDir = "/mydir";
Path dir = Paths.get(watchedDir);
// 3 register on the events you need to watch
WatchKey watchKey = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
...
// 4 wait for changes, generally inside a loop
watchKey = watchService.take();
方法 take 在可用时返回一个 watch key,否则等待。
关于java - 线程等待直到文件修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093852/