WatchService监听文件变化
1 package chapter3; 2 3 import java.io.IOException; 4 import java.nio.file.FileSystems; 5 import java.nio.file.Paths; 6 import java.nio.file.StandardWatchEventKinds; 7 import java.nio.file.WatchEvent; 8 import java.nio.file.WatchKey; 9 import java.nio.file.WatchService; 10 import java.util.List; 11 12 public class WatchServiceTest { 13 14 public static void main(String[] args) throws IOException, InterruptedException { 15 WatchService ws = FileSystems.getDefault().newWatchService(); 16 Paths.get("C:/").register(ws, StandardWatchEventKinds.ENTRY_CREATE); 17 while (true) { 18 WatchKey wk = ws.take(); 19 List<WatchEvent<?>> weList = wk.pollEvents(); 20 for (WatchEvent<?> we : weList) { 21 System.out.println(we.context() + " 文件发生了: " + we.kind() + "事件!"); 22 } 23 boolean valid = wk.reset(); 24 if (!valid) { 25 break; 26 } 27 } 28 } 29 30 }
原文:http://www.cnblogs.com/djjwwz/p/5215252.html