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/

原文链接:How to watch a directory in Java?

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容