The Path class of NIO.2 provides the following method to listen to changes in the file system.
Register (WatcherService watcher, WatchEvent. Kind <?>... Events): Use watcher to listen for file changes under the directory represented by this path. The event parameter specifies the types of events to listen.
WatchService has three methods to listen for file change events in the directory.
WatchKey poll (): gets the next WatchKey. If no WatchKey is generated, null is returned immediately;
WatcheKey poll (long timeout, TimeUnit unit): try to wait for the timeout time to get the next WatchKey;
WatchKey take (): gets the next WatchKey, and waits until it does not happen;
If the program needs to monitor all the time, use the take () method. If the program only needs to monitor the specified time, use the poll method.
[Java]
// Www.heatpress123.net
Import java. nio. file. FileSystems;
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 Test {
Public static void main (String [] args) throws Exception
{
WatchService watchService = FileSystems. getDefault (). newWatchService ();
Paths. get ("C:/"). register (watchService,
StandardWatchEventKinds. ENTRY_CREATE,
StandardWatchEventKinds. ENTRY_DELETE,
StandardWatchEventKinds. ENTRY_MODIFY );
While (true)
{
WatchKey key = watchService. take ();
For (WatchEvent <?> Event: key. pollEvents ())
{
System. out. println (event. context () + "" + event. kind () + "event ");
}
If (! Key. reset ())
{
Break;
}
}
}
}