How to watch a directory in Java?

vijaysrj

Vijay SRJ

Posted on December 23, 2020

How to watch a directory in Java?

You can watch a folder/directory on your server or computer easily using Watch API provided by Java.

Below is the algorithm:
STEP1: Create a watch service

      WatchService watchService = FileSystems.getDefault().newWatchService();
Enter fullscreen mode Exit fullscreen mode

STEP2: Get the path of the folder you want to monitor

STEP3: Register the folder path with the service

STEP4: Poll for events in an infinite loop

STEP5: For each event get the file name from the event context

STEP6: For each event check its type

STEP7: For each type of event perform the action you want.

STEP8: Reset the watch key used to poll events.

Explained in detail with code here:
https://fullstackdeveloper.guru/2020/12/23/how-to-watch-a-folder-directory-or-changes-using-java/

πŸ’– πŸ’ͺ πŸ™… 🚩
vijaysrj
Vijay SRJ

Posted on December 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related