简体   繁体   English

有没有办法在到达文件末尾时阻止读取 util 有新数据写入 java 中的文件

[英]is there any way to block read when reached end of file util there is new data write to file in java

I have 2 java processes, process A writes data to file, process B reads data from file.我有 2 个 java 进程,进程 A 将数据写入文件,进程 B 从文件中读取数据。 Sometimes process A is not running, process B needs to read existing data from file,so I cannot use socket instead of file.有时进程 A 没有运行,进程 B 需要从文件中读取现有数据,所以我不能使用套接字代替文件。

The problem is, when B reach to end of file, read function returns immediately,if I retry without sleep() , CPU usage is 100% even if there is no new data.问题是,当 B 到达文件末尾时,读取 function 立即返回,如果我在没有sleep()的情况下重试,即使没有新数据,CPU 使用率也是 100%。 If I try with sleep() , response time and performance is not good.如果我尝试使用sleep() ,响应时间和性能都不好。

Is there any way to block read when reached end of file until there is new data written to file, as if I was using socket?有没有办法在到达文件末尾时阻止读取,直到有新数据写入文件,就像我使用套接字一样?

Try using WatchService API of java.nio package.尝试使用 java.nio package 的 WatchService API。 In this, you can create watcher for any modifications in the directory.在此,您可以为目录中的任何修改创建观察者。 There will different events for different modifications based on which you can trigger the read.不同的修改会有不同的事件,您可以根据这些事件触发读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM