如何检测java中的文件系统已经改变

我想知道如何在java中有效地实现文件系统更改? 假设我在文件夹中有一个文件并修改该文件。 我希望尽快通过java通知这个变化(如果可能的话,不经常轮询)。

因为我认为我可以每隔几秒调用java.io.file.lastModified但我根本不喜欢该解决方案的声音。

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) 

看看JNotify ,它执行这种类型的监控。

Java 7将为这类工作提供一些更高级的API( WatchService ),这将消除对支持此操作的操作系统的轮询。

我怀疑有一种纯粹的java方法来做到这一点。 操作系统提供API来监视文件系统的活动。 您可能需要调用这些API。

使用JNotify,你需要做的就是在buildpath中添加jnotify.jar并放入两个dll文件,即jnotify.dll jnotify_64bit.dll和jdk的lib里面。 一个演示程序是

 package jnotify; import net.contentobjects.jnotify.JNotify; import net.contentobjects.jnotify.JNotifyListener; public class MyJNotify { public void sample() throws Exception { String path = "Any Folder location here which you want to monitor"; System.out.println(path); int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; boolean watchSubtree = true; int watchID = JNotify .addWatch(path, mask, watchSubtree, new Listener()); Thread.sleep(1000000); boolean res = JNotify.removeWatch(watchID); if (!res) { System.out.println("Invalid"); } } class Listener implements JNotifyListener { public void fileRenamed(int wd, String rootPath, String oldName, String newName) { print("renamed " + rootPath + " : " + oldName + " -> " + newName); } public void fileModified(int wd, String rootPath, String name) { print("modified " + rootPath + " : " + name); } public void fileDeleted(int wd, String rootPath, String name) { print("deleted " + rootPath + " : " + name); } public void fileCreated(int wd, String rootPath, String name) { print("created " + rootPath + " : " + name); } void print(String msg) { System.err.println(msg); } } public static void main(String[] args) { try { new MyJNotify().sample(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

有一个Apache软件包可以进行文件系统监控:commons.io.monitor。

文档

一个例子

据我所知,你仍然需要轮询,尽管你可以控制频率。