Java FileAlterationMonitor-class And Method Code Example


Here is an example of how to use the FileAlterationMonitor class from the Apache Commons IO library in Java to monitor a directory for changes:

import java.io.File;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class FileMonitorExample {

    public static void main(String[] args) throws Exception {
        // Define the directory to be monitored
        String dir = "/path/to/directory";
        File directory = new File(dir);

        // Create a new observer
        FileAlterationObserver observer = new FileAlterationObserver(directory);

        // Create a new monitor and register the observer
        FileAlterationMonitor monitor = new FileAlterationMonitor(1000);
        monitor.addObserver(observer);

        // Start the monitor
        monitor.start();
    }
}

This example will monitor the directory located at /path/to/directory and check for changes every 1000 milliseconds (1 second). You can add listener to observer to handle file modification and deletion events.