How to watch a directory in Java?
Vijay SRJ
Posted on December 23, 2020
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();
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/
π πͺ π
π©
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.