Java 监测目录

来源:互联网 发布:淘宝不能卖烟吗 编辑:程序博客网 时间:2024/04/29 21:42

今天看书看到Java监测目录的一段代码,测试了一下,在此记录:

public static void FolderWatcher(String filePath){Path path = Paths.get(filePath);// To check file exist.if (!path.toFile().exists())throw new IllegalArgumentException("The file path is not exist.");try{WatchService watcher = FileSystems.getDefault().newWatchService();WatchKey key = path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);while (true){key = watcher.take();for (WatchEvent<?> event : key.pollEvents()){System.out.println(event.context() + "  " + event.kind());}key.reset();}} catch (IOException | InterruptedException e){e.printStackTrace();}}

代码中StandardWatchEventKinds类参数可以根据选择添加。

0 0
原创粉丝点击