线程等待直到文件修改

fho*_*yer 1 java multithreading file

我正在寻找一种方法来睡眠线程,直到在Java 1.8中修改文件(如在文件被触摸和/或更改).基本上,这个线程必须读取文件的内容,警惕任何更改,但不能吸收核心只是为了读取文件,等待,再次读取,等待等.

理想情况下,线程会以与并发阻塞队列将线程置于休眠状态相同的方式阻塞,直到有从队列中删除的内容为止.

有任何想法吗?

Dav*_*INO 6

您可以使用NIOWatchService:

监视已注册对象的更改和事件的监视服务.例如,文件管理器可以使用监视服务来监视目录以进行更改,以便在创建或删除文件时它可以更新其文件列表的显示.

要使用它,您需要:

// 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();
Run Code Online (Sandbox Code Playgroud)

方法在可用时返回监视键,否则等待.