Java 8 Watchservice Example, easy in 10 minutes

Today, We walk you through a Java 8 Watchservice Example in easy steps. You will know how to watch a directory along with subdirectories and files inside there. Beside, we implement a full java program that demonstrates all watched events like ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY. Now, let’s dig into it.

Java 8 Watchservice Example

Register a single directory to Java watcher

We create a method that accepts the path of a directory where we want to watch and which events want to watch like ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY.

Watch directory, sub-directories, and files

We will traversal recursively all directory and subdirectories from a parent directory and call the registerDir method for each directory we encounter.

Watching for change events

We use pollEvents()method to get changes occurred on directory and file inside it.

If you are using the same key to get events multiple times in a loop, you must call watchKey.reset() method that reset key in ready state again.

Watching a created directory event

Anytime, a new directory is created, it should be registered with watchservice, look into code snippet below.

Creating a program for Java 8 Watchservice Example

Now, we create a full program that demonstrates all the cases above. This program will watch a directory, on my local e.g: D:/backup. Here is detail implementation of Java 8 Watchservice Example:

Before running the program, the directory D:/backup contains some things like below

Java 8 Watchservice Example

Now, we run the above program then rename a file in that directory and create a new folder then rename that folder. We will see the output below:

Java 8 Watchservice Example

That’s all about Java 8 Watchservice Example. You may be interested in other Java 8 tutorials

.

If you find this post useful, don't hesitate to share it with your friends or other people for growing knowledge together and is an effort to contribute us.

References

Java Watchservice Interface

Download complete source code

java8-watchservice-example.zip (6 downloads)
Please share it if you found this useful
Hide Buttons