之前想过对一些文件操作最好能够监控,从而通过文件变更监控来解决系统耦合,比如某公司就是通过监控binlog变化来同步数据库,从java7开始提供了系统级别的工具,使文件变更监控变的更简单
public class Test { public static void main(String[] args) { WatchService watcher = null; try { watcher = FileSystems.getDefault().newWatchService(); Path dir = FileSystems.getDefault().getPath("E:\\"); WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { System.out.println(event.kind().name()); System.out.println(event.context()); System.out.println("00-------------------00"); } key.reset(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
上面是一个简单的例子