Course contentsShow
← Java
Lesson 2095 of 2,87041. NIO.2 and the Path APIFree lesson

Creating a WatchService Instance

Using FileSystem.newWatchService() to create a WatchService for monitoring file system events.

Creating a WatchService Instance

You'll learn how to initialize a WatchService object to begin monitoring file system changes in your Java application.

What Is a WatchService?

Think of a WatchService as a security guard that watches specific directories for you. Before this guard can start monitoring, you need to hire them—that's what creating the instance does. The WatchService is the core component of the NIO.2 watching API that enables your application to receive notifications when files or directories change.

Creating the Instance

To create a WatchService, you obtain it from a FileSystem object using the newWatchService() method:

import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.WatchService;
import java.io.IOException;

// Get the default file system
FileSystem fileSystem = FileSystems.getDefault();

// Create a WatchService instance
try (WatchService watchService = fileSystem.newWatchService()) {
    // WatchService is now ready to monitor directories
    // (registration and polling come next)
} catch (IOException e) {
    e.printStackTrace();
}

Key Details

The newWatchService() method may throw an IOException if the watch service cannot be created (for example, if the operating system doesn't support file watching).

The WatchService implements Closeable, so you should use try-with-resources to ensure proper cleanup. When closed, the service releases any system resources and invalidates registered directories.

At this stage, the WatchService exists but isn't watching anything yet—you'll need to register specific paths to monitor in subsequent steps.

Key Takeaway: Use FileSystems.getDefault().newWatchService() to create a WatchService instance that can monitor file system events; always manage it with try-with-resources for proper resource cleanup.