public static void main(String[] args) throws IOException { try { WatchService watcher = FileSystems.getDefault().newWatchService(); Path watchedDir = Paths.get("C:\\Users\\Administrator\\workspace\\test"); WatchKey key = watchedDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY); System.out.println("Watching "+ watchedDir); while(true) { key = watcher.take(); for(WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); WatchEvent<Path> ev = (WatchEvent<Path>)event; Path pathName = ev.context(); if(kind == StandardWatchEventKinds.ENTRY_MODIFY) System.out.println(pathName + " modified!"); else if(kind == StandardWatchEventKinds.ENTRY_DELETE) System.out.println(pathName+" deleted"); else { System.out.println(pathName + "created"); } } key.reset(); } } catch (InterruptedException e) { // TODO 自动生成的 catch 块
e.printStackTrace(); } }输出:Watching C:\Users\Administrator\workspace\test
test7.txt deleted
test8.txtcreated
test8.txt modified!
newFilecreated
newFile modified!
newFile modified!
newDircreated
newDir modified!
.newFile.swpcreated
.newFile.swp modified!
.newFile.swpxcreated
.newFile.swpx modified!
.newFile.swpx deleted
.newFile.swp deleted
.newFile.swpcreated
.newFile.swp modified!
.newFile.swp modified!
.newFile.swp modified!
newFile~created
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile modified!
newFile modified!
newFile~ deleted
.newFile.swp modified!
.newFile.swp deleted
newDir deleted
newFile deleted
test8.txt deleted
新建文件夹 deleted