I'm very new to Java. I found and example of a folder watcher service that I wanted to use for a simple app but no matter what I do I cannot get it to work. As best as I can figure out is that I'm not assigning the path variable properly.
I'd also be very grateful if someone could explain why I have to specify the full java.nio.file.StandardWatchEventKind.ENTRY_CREATE even though I do the import at the beginning.
import java.io.*; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKind.*; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; public class FileWatcher { public static void main(String args[]) throws InterruptedException { FileSystem fs = FileSystems.getDefault(); WatchService watcher = null; try { watcher = fs.newWatchService(); } catch (IOException ex) { System.err.println(ex); } Path dir = FileSystems.getDefault().getPath("H:\\Download"); System.out.println(dir.toString()); try { WatchKey key = dir.register(watcher, java.nio.file.StandardWatchEventKind.ENTRY_CREATE); } catch (IOException x) { System.err.println(x); } for (;;) { //wait for key to be signaled WatchKey key = watcher.take(); for (WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); //The filename is the context of the event. WatchEvent<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); System.out.println(ev.kind() + " : " + ev.context()); } //Reset the key -- this step is critical if you want to receive //further watch events. If the key is no longer valid, the directory //is inaccessible so exit the loop. boolean valid = key.reset(); System.out.println(valid); if (!valid) { break; } } } }