eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this article, we are going to explore the WatchService interface of Java NIO.2 filesystem APIs. This is one of the lesser known features of the newer IO APIs that were introduced in Java 7 alongside FileVisitor interface.

To use the WatchService interface in your applications, you need to import the appropriate classes:

import java.nio.file.*;

2. Why Use WatchService

A common example to understand what the service does is actually the IDE.

You might have noticed that the IDEs always detects a change in source code files that happen outside itself. Some IDE’s inform you using a dialog box so that you can choose to reload the file from the filesystem or not, others simply update the file in the background.

Similarly, newer frameworks such as Play also does hot reloading of the application code by default – whenever you’re performing edits from any editor.

These applications employ a feature called file change notification that is available in all filesystems.

Basically, we can write code to poll the filesystem for changes on specific files and directories. However, this solution is not scalable especially if the files and directories reach the hundreds and thousands.

In Java 7 NIO.2, the WatchService API provides a scalable solution for monitoring directories for changes. It has a clean API and is so well optimized for performance that we don’t need to implement our own solution.

3. How Does the Watchservice Work?

To use the WatchService features, the first step is to create a WatchService instance using the java.nio.file.FileSystems class:

WatchService watchService = FileSystems.getDefault().newWatchService();

Next, we have to create the path to the directory we want to monitor:

Path path = Paths.get("pathToDir");

After this step, we have to register the path with watch service. There are two important concepts to understand at this stage. The StandardWatchEventKinds class and the WatchKey class. Take a look at the following registration code just to understand where each fall. We will follow this with explanations of the same:

WatchKey watchKey = path.register(
  watchService, StandardWatchEventKinds...);

Notice only two important things here: First, the path registration API call takes the watch service instance as the first parameter followed by variable arguments of StandardWatchEventKinds. Secondly, the return type of the registration process is a WatchKey instance.

3.1. The StandardWatchEventKinds

This is a class whose instances tell the watch service the kinds of events to watch for on the registered directory. There are currently four possible events to watch for:

  • StandardWatchEventKinds.ENTRY_CREATE – triggered when a new entry is made in the watched directory. It could be due to the creation of a new file or renaming of an existing file.
  • StandardWatchEventKinds.ENTRY_MODIFY – triggered when an existing entry in the watched directory is modified. All file edit’s trigger this event. On some platforms, even changing file attributes will trigger it.
  • StandardWatchEventKinds.ENTRY_DELETE – triggered when an entry is deleted, moved or renamed in the watched directory.
  • StandardWatchEventKinds.OVERFLOW – triggered to indicate lost or discarded events. We won’t focus much on it

3.2. The WatchKey

This class represents the registration of a directory with the watch service. Its instance is returned to us by the watch service when we register a directory and when we ask the watch service if any events we registered for have occurred.

Watch service offers us no callback methods which are called whenever an event occurs. We can only poll it in a number of ways to find this information.

We can use the poll API:

WatchKey watchKey = watchService.poll();

This API call returns right away. It returns the next queued watch key any of whose events have occurred or null if no registered events have occurred.

We can also use an overloaded version that takes a timeout argument:

WatchKey watchKey = watchService.poll(long timeout, TimeUnit units);

This API call is similar to the previous one in return value. However, it blocks for timeout units of time to give more time within which an event may occur instead of returning null right away.

Finally, we can use the take API:

WatchKey watchKey = watchService.take();

This last approach simply blocks until an event occurs.

We must note something very important here: when the WatchKey instance is returned by either of the poll or take APIs, it will not capture more events if it’s reset API is not invoked:

watchKey.reset();

This means that the watch key instance is removed from the watch service queue every time it is returned by a poll operation. The reset API call puts it back in the queue to wait for more events.

The most practical application of the watcher service would require a loop within which we continuously check for changes in the watched directory and process accordingly. We can use the following idiom to implement this:

WatchKey key;
while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        //process
    }
    key.reset();
}

We create a watch key to store the return value of the poll operation. The while loop will block until the conditional statement returns with either a watch key or null.

When we get a watch key, then the while loop executes the code inside it. We use the WatchKey.pollEvents API to return a list of events that have occurred. We then use a for each loop to process them one by one.

After all the events are processed, we must call the reset API to enqueue the watch key again.

4. Directory Watching Example

Since we have covered the WatchService API in the previous subsection and how it works internally and also how we can use it, we can now go ahead and look at a complete and practical example.

For portability reasons, we are going to watch for activity in the user home directory, which should be available on all modern operating systems.

The code contains only a few lines of code so we will just keep it in the main method:

public class DirectoryWatcherExample {

    public static void main(String[] args) {
        WatchService watchService
          = FileSystems.getDefault().newWatchService();

        Path path = Paths.get(System.getProperty("user.home"));

        path.register(
          watchService, 
            StandardWatchEventKinds.ENTRY_CREATE, 
              StandardWatchEventKinds.ENTRY_DELETE, 
                StandardWatchEventKinds.ENTRY_MODIFY);

        WatchKey key;
        while ((key = watchService.take()) != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println(
                  "Event kind:" + event.kind() 
                    + ". File affected: " + event.context() + ".");
            }
            key.reset();
        }
    }
}

And that is all we really have to do. Now you can run the class to start watching a directory.

When you navigate to the user home directory and perform any file manipulation activity like creating a file or directory, changing contents of a file or even deleting a file, it will all be logged at the console.

For instance, assuming you go to user home, right click in space, select `new – > file` to create a new file and then name it testFile. Then you add some content and save. The output at the console will look like this:

Event kind:ENTRY_CREATE. File affected: New Text Document.txt.
Event kind:ENTRY_DELETE. File affected: New Text Document.txt.
Event kind:ENTRY_CREATE. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.
Event kind:ENTRY_MODIFY. File affected: testFile.txt.

Feel free to edit the path to point to any directory you want to watch.

4.1. Watching a Single File

The WatchService API works at the directory level, meaning we can’t directly register a single file. However, we can filter events for a specific file. Let’s tweak our example, assuming we want to watch a single file called config.properties located in the user’s home directory:

Path fileToWatch = path.resolve("config.properties");
for (WatchEvent<?> event : key.pollEvents()) {
    Path changed = (Path) event.context();

    if (changed.equals(fileToWatch.getFileName())) {
        System.out.println(
          "Event kind: " + event.kind() 
            + ". File affected: " + changed);
    }
}

Here, event.context() returns the relative path of the changed entry within the watched directory, so we compare it with fileToWatch.getFileName() instead of the full path. When we create, modify, and delete the file, the output will look like this:

Event kind: ENTRY_CREATE. File affected: config.properties
Event kind: ENTRY_MODIFY. File affected: config.properties
Event kind: ENTRY_DELETE. File affected: config.properties

5. Conclusion

In this article, we have explored some of the less commonly used features available in the Java 7 NIO.2 – filesystem APIs, particularly the WatchService interface.

We have also managed to go through the steps of building a directory watching application to demonstrate the functionality.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)