The java.nio.file package provides a file change notification API, called the Watch Service API. This API allows you to register a directory (or directories) with the watch service — when registering you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When one comes in, it is handled as needed.

//Verify that the new file is a text file. try { //Resolve the filename against the directory. //If the filename is "test" and the directory is "foo", //the resolved name is "test/foo". Path child = dir.resolve(filename); if (!Files.probeContentType(child).equals("text/plain")) { System.err.format("New file '%s' is not a plain text file.%n", filename); continue; } } catch (IOException x) { System.err.println(x); continue; }

//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(); if (!valid) { break; }}

When registering an object with the watch service, you specify the types of events you want to monitor. The supported StandardWatchEventKind event types are:

* ENTRY_CREATE — a directory entry is created. * ENTRY_DELETE — a directory entry is deleted. * ENTRY_MODIFY — a directory entry is modified; * OVERFLOW — indicates that events may have been lost or discarded. You do not have to register for this event to receive it.

The following code snippet shows how to register a Path instance for all three event types: