DEV Community

Vijay SRJ
Vijay SRJ

Posted on

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/

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

I think there's an inotify library for Java. That would take care of this for you and mean you didn't have to go through the expensive "poll for events in an infinite loop" step.

Collapse
 
vijaysrj profile image
Vijay SRJ

thanks Ben..will check that.