.NET Framework里面有个类叫FileSystemWatcher, 主要是监视一个目录里面文件的变化,最简单的用法如下
FileSystemWatcher fswatcher =new FileSystemWatcher ();
fswatcher.Path =this.WatchFolder ;
fswatcher .Filter ="*.jpg;";
fswatcher.Created +=new FileSystemEventHandler(fswatcher_Created);
fswatcher.Path =this.WatchFolder ;
fswatcher .Filter ="*.jpg;";
fswatcher.Created +=new FileSystemEventHandler(fswatcher_Created);
然后就在fswatch_Created函数里面写如果文件出现变化,要做什么处理。这个MSDN里面的例子写得很清楚。不过我在用这个类的时候总觉得很不爽的就是他只能监视一种类型的文件,比如*.jpg, *.txt,如果我希望他即监视*.jpg又监视*.bmp就不行了,我尝试过使用DOS里常用的*.jpg;*.bmp的写法,发现他就变得什么都干不了了。解决的办法可能只有一个,就是用2个FileSystemWatcher对象。不过这样或许会消耗更多的资源。不知道.NET Framework 2.0里面有没有什么改进。
顺便想到在java里有没有相应的类,不过没找到。传统的做法估计就是hook 操作系统了,在windows下用这几个API:
Private Declare Function FindFirstChangeNotification Lib "kernel32" Alias "FindFirstChangeNotificationA" _ (ByVal lpPathName As String, ByVal bWatchSubtree As Long, ByVal dwNotifyFilter As Long) As Long
Private Declare Function FindCloseChangeNotification Lib "kernel32" (ByVal hChangeHandle As Long) As Long
Private Declare Function FindNextChangeNotification Lib "kernel32" (ByVal hChangeHandle As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function FindCloseChangeNotification Lib "kernel32" (ByVal hChangeHandle As Long) As Long
Private Declare Function FindNextChangeNotification Lib "kernel32" (ByVal hChangeHandle As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
有个MVP写了完全在vb下用api实现的算法,http://vbnet.mvps.org/index.html?code/fileapi/watchedfolder.htm,可能速度上要比FileWatcher更高,估计.NET里的实现和这个也差不多。