java - 线程等待直到文件修改

标签 java multithreading file

我正在寻找一种在 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/

相关文章:

java - 如何将 MainView 注册到另一个 View 触发的 ComponentEvent?

java - 需要persistence.xml属性标签来设置sybase数据库驱动程序版本

java - Wait()、Notify()、计时器和 Jbuttons

java - List<String> 的 add 方法是否线程安全?

java - 遍历树找到节点

java - 日期时间解析不强制执行格式

java - 迭代时向 HashSet 添加元素

c# - 有没有一种编程方式来确定文件是否正在使用?

java - 如何将图库中的图像作为文件参数

python - 使用控制台启动程序时无法写入文件