Created
November 9, 2018 12:54
-
-
Save arleighdickerson/932abbb82ffb3ddb84a08a440a3c2621 to your computer and use it in GitHub Desktop.
This file contains 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
package io.arleigh.reporting; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.nio.file.FileSystems; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.nio.file.StandardWatchEventKinds; | |
import java.nio.file.WatchEvent; | |
import java.nio.file.WatchKey; | |
import java.nio.file.WatchService; | |
public class DirectoryWatcherExample { | |
private static void printContents(Path path) { | |
//using NIO.2 unbuffered stream | |
int n; | |
try (InputStream in = Files.newInputStream(path)) { | |
while ((n = in.read()) != -1) { | |
System.out.print((char) n); | |
} | |
} catch (IOException e) { | |
System.err.println(e); | |
} | |
} | |
public static void main(String[] args) { | |
try { | |
WatchService watchService = FileSystems.getDefault().newWatchService(); | |
String home = System.getProperty("user.home"); | |
System.out.println(home); | |
Path path = Paths.get(home); | |
path.register( | |
watchService, | |
StandardWatchEventKinds.ENTRY_CREATE, | |
StandardWatchEventKinds.ENTRY_DELETE, | |
StandardWatchEventKinds.ENTRY_MODIFY); | |
WatchKey key; | |
while ((key = watchService.take()) != null) { | |
Path dir = (Path) key.watchable(); | |
for (WatchEvent<?> event : key.pollEvents()) { | |
System.out.println( | |
"Event kind:" + event.kind() | |
+ ". File affected: " + event.context() + "."); | |
// Path fullPath = dir.resolve(((WatchEvent<Path>) event).context()); | |
// printContents(fullPath); | |
} | |
key.reset(); | |
} | |
} catch (Exception e) { | |
System.exit(1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment