介绍对于监听文件变化的几种方式
使用场景
监听指定目录的变化,发起主动的通知。
java的 FileAlterationMonitor
主要原理:
使用commons-io库中的FileAlterationMonitor来监听文件变化,并发出通知
这个本质上也是轮询。通过观察者模式进行通知。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class FileMonitor { public static void main(String[] args) { String dir="D:\\SOFT\\"; long interval = TimeUnit.SECONDS.toMillis(1); FileAlterationMonitor moitor = new FileAlterationMonitor(interval); FileAlterationObserver observer = new FileAlterationObserver(new File(dir)); moitor.addObserver(observer); observer.addListener(new FileAlterationListenerAdaptor() { @Override public void onFileCreate(File file) { System.out.println(file.getName()+" create"); } }); try { moitor.start(); } catch (Exception e) { e.printStackTrace(); } } }
|
pom.xml add dependency
1 2 3 4 5
| <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
|
python 的watchdog
依赖
需要安装watchdog依赖,pip install watchdog
继承LoggingEventHandler
类,可以其中处理文件变化消息
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import sys import time import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler
class extractor(LoggingEventHandler):
def on_created(self, event): super(LoggingEventHandler, self).on_created(event) what = 'directory' if event.is_directory else 'file' logging.info("extractor created %s: %s", what, event.src_path)
if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = extractor()
observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
|
linux环境下的inotify
这个一般结合rsync用。
可参考这篇文章 An Introduction to File System Monitoring Tools
总结