This question already has an answer here:
-
Watching a Directory for Changes in Java
6 answers
I'm planning to make a program to keep checking the directory whether files exists or not. If not then wait for some time (say 5 mins sleep) and then again checks the directory. The program must keep running and should not end.
I've thought of make a multi-thread program. But don't know how exactly I can implement it. And if any other options are available then please let me know.
To implement this functionality, called file change notification, a program must be able to detect what is happening to the relevant directory on the file system. One way to do so is to poll the file system looking for changes, but this approach is inefficient. It does not scale to applications that have hundreds of open files or directories to monitor.
The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.
You can do so by creating a watch service and registering for various events. More details can be found here at Oracle tutorial doc.
Similar question on SO here