How to Watch a Directory for Changes in Java ?
Last Updated :
26 Feb, 2024
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
import java.io.IOException;
import java.nio.file.*;
public class FileData {
public static void main(String[] args) {
try {
Path directoryPath = Paths.get( "./" );
WatchService watchService = FileSystems.getDefault().newWatchService();
directoryPath.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
System.out.println( "Watching directory: " + directoryPath);
while ( true ) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents())
{
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());
}
}
key.reset();
}
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
}
}
|
Output:
Below is the output video for better understanding of the result.
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.
Share your thoughts in the comments
Please Login to comment...