Java monitoring file changes

Source: Internet
Author: User

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;
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.