Created
November 18, 2014 19:57
-
-
Save ansig/73c0e7672ffa4f7049af to your computer and use it in GitHub Desktop.
Watch a directory for changes using a WatchService.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.nio.file.*; | |
import static java.nio.file.StandardWatchEventKinds.*; | |
/** | |
* Watch a directory for changes using a WatchService. | |
*/ | |
public class DirWatcher { | |
public static void main(String[] args) throws IOException { | |
WatchService watchService = FileSystems.getDefault().newWatchService(); | |
Path homeDir = Paths.get(System.getProperty("user.home")); | |
homeDir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); | |
System.out.printf("Watch service registered for: %s%n", homeDir); | |
WatchKey eventKey; | |
while(true) { | |
try { | |
eventKey = watchService.take(); | |
} catch (InterruptedException ie) { | |
System.out.printf("Watch service interrupted!%n"); | |
return; | |
} | |
for (WatchEvent<?> event : eventKey.pollEvents()) { | |
WatchEvent.Kind eventKind = event.kind(); | |
if (eventKind == OVERFLOW) { | |
System.out.printf("Overflow event"); | |
continue; | |
} | |
WatchEvent<Path> specEvent = (WatchEvent<Path>)event; | |
Path filename = specEvent.context(); | |
if (eventKind == ENTRY_CREATE) { | |
System.out.printf("CREATED %s%n", filename); | |
} else if (eventKind == ENTRY_MODIFY) { | |
System.out.printf("MODIFIED %s%n", filename); | |
} else if (eventKind == ENTRY_DELETE) { | |
System.out.printf("DELETED %s%n", filename); | |
} | |
} | |
eventKey.reset(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment