java中如何检测文件系统已更改
我想知道如何在java中有效地实现文件系统更改?假设我在文件夹中有一个文件并修改该文件。我希望尽快得到 java 的有关此更改的通知(如果可能的话,不要频繁轮询。)。
因为我想我可以调用
alfred@alfred-laptop:~/testje$ java -version
java version "1.6.0_18"
Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode)
I would like to know how to efficiently implement filesystem changes in java? Say I got a file in a folder and modify that file. I would like to be notified by java about this change as soon as possible(no frequently polling if possible.).
Because I think I could call java.io.file.lastModified every few seconds but I don't like the sound of that solution at all.
alfred@alfred-laptop:~/testje$ java -version
java version "1.6.0_18"
Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看一下JNotify,它执行这种类型的监视。
Java 7 将针对此类提供一些更高级的 API (WatchService)这将消除对支持此功能的操作系统的轮询。
Take a look at JNotify, which performs this type of monitoring.
Java 7 will have some more advanced APIs (WatchService) for this sort of work which will eliminate polling on the OSes that support this.
我怀疑是否有一种纯java方法可以做到这一点。操作系统提供 API 来监视文件系统活动。您可能需要调用这些 API。
I doubt that there is a pure java way to do this. Operating systems offer APIs to monitor file system a activity. You will probably need to call those APIs.
使用JNotify,您需要做的就是在buildpath中添加jnotify.jar并放入两个dll文件,即jnotify.dll jnotify_64bit.dll和jdk的lib内部。演示程序是
Use JNotify, All you need to do is add jnotify.jar in buildpath and put two dll files i.e jnotify.dll jnotify_64bit.dll and inside lib of jdk. A demo program is
有一个 Apache 软件包可以进行文件系统监控:commons.io.monitor。
文档
示例
据我所知,尽管您可以控制频率,但您仍然需要进行轮询。
There is an Apache package that does file system monitoring: commons.io.monitor.
Documentation
An example
From what I can tell, you will still need to poll albeit you have control over the frequency.