有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于更改文本文件内容的java事件

我的java程序需要知道文本文件的内容是否发生了变化。目前我正在使用File.lastModified()方法来做这件事,但理想情况下我不想执行检查。相反,我希望在每次修改文件时触发一个事件。有没有第三方图书馆可以提供这种服务?我听说它可以用apache file descriptors来完成,但找不到任何关于它的信息


共 (4) 个答案

  1. # 1 楼答案

    试试Apache的DefaultFileMonitor

    您只需将相关文件添加到需要监视的文件列表中,然后启动监视线程

    如果文件已被更改或删除,则应触发OnChange事件

  2. # 2 楼答案

    有很多因素可能会决定你的解决方案。文件更新的频率,信息的类型等等

    我的建议是要么使用Java 7标准,要么使用Apache事实上的标准(如果需求不允许使用Java 7解决方案)


    Apache配置

    If it is a file that is kind of property information, a configuration, then you might want to look at Apache commons configuration. Which gives a refresh method each time the file is updated, to reload your configuration, etc. http://commons.apache.org/proper/commons-configuration/userguide/howto_events.html#An_example


    Java7,WatchService

    If you use Java 7, look at the WatchService, link http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html


    Apache IO

    If you dont want to use Java 7, and the file is not a configuration (which is better to use commons configuration that way), then you might want to look at FileAlterationObserver from Apache io. http://commons.apache.org/proper/commons-io/

  3. # 3 楼答案

    您可以使用新的Java 7 WatchService实现这一点。这使您能够监视目录,并收到创建、修改和删除事件的通知