Open In App

How to Watch a Directory for Changes in Java ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to watch the directory changes through the Java programming language. Java provides a robust and efficient way to monitor directories for changes through the java.nio.file package. The WatchService API allows developers to receive notifications about various events such as file creation, deletion, and modification within a specific directory.

Import Required Packages

The WatchService interface is available in the java.nio.file package. We can use the WatchService interface using this file extension.

Package:

import java.nio.file.* 

Create the instance of WatchService

We can use the WatchService features. By creating the instance of the WatchService instance the java.nio.file File System class.

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

Steps for Implementation

  • Step 1: Create a Watch Service
  • Step 2: Specify the directory which is supposed to be watched.
  • Step 3: Register the directory path for specific events.
  • Step 4: Poll the events in an infinite loop.
  • Step 5: From the event context get the file name for each event.
  • Step 6: Check the type for each event.
  • Step 7: Perform actions for each type of event.
  • Step 8: Reset the watch key.

Example to Watch a Directory for Changes in Java

The following program demonstrates the current directory changes using the WatchService.

Java




// Java Program
import java.io.IOException;
import java.nio.file.*;
 
// Driver Class
public class FileData {
    // Main Function
    public static void main(String[] args) {
        try {
            // Specify the directory which supposed to be watched
            Path directoryPath = Paths.get("./");
 
            // Create a WatchService
            WatchService watchService = FileSystems.getDefault().newWatchService();
 
            // Register the directory for specific events
            directoryPath.register(watchService,
                    StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE,
                    StandardWatchEventKinds.ENTRY_MODIFY);
 
            System.out.println("Watching directory: " + directoryPath);
 
            // Infinite loop to continuously watch for events
            while (true) {
                WatchKey key = watchService.take();
 
                for (WatchEvent<?> event : key.pollEvents())
                {
                    // Handle the specific event
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE)
                    {
                        System.out.println("File created: " + event.context());
                    }
                    else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE)
                    {
                        System.out.println("File deleted: " + event.context());
                    }
                    else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY)
                    {
                        System.out.println("File modified: " + event.context());
                    }
                }
 
                // To receive further events, reset the key
                key.reset();
            }
 
        }
        catch (IOException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}


Output:

Below is the output video for better understanding of the result.

video-copy-1

StandardWatchEventKinds

  • StandardWatchEventKinds.ENTRY_CREATE: When a new entry is made in the watch directory, it will prompt.
  • StandardWatchEventKinds.ENTRY_DELETE: When an entry is deleted or moved in the watched directory, this will prompt.
  • StandardWatchEventKinds.ENTRY_MODIFY: When an existing entry is modified in watched directory, this will prompt.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads