Java TimestampedObserver-class And Method Code Example


Here is an example of how to use the TimestampedObserver class from the Apache Commons IO library to monitor a file for changes and log the timestamp and action taken in Java:

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.TimestampedObserver;

public class FileMonitorExample {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("path/to/folder");
        FileAlterationObserver observer = new FileAlterationObserver(path);
        observer.addListener(new TimestampedObserver());
        FileAlterationMonitor monitor = new FileAlterationMonitor(1000);
        monitor.addObserver(observer);
        monitor.start();
    }
}

In this example, a FileAlterationObserver is created to monitor a directory located at "path/to/folder" for changes. The observer is given a TimestampedObserver as a listener, which will log the timestamp and action taken (create, modify, delete) whenever a file in the directory is changed.

A FileAlterationMonitor is then created and set to check for changes every 1000 milliseconds. The observer is added to the monitor and the monitor is started.

The TimestampedObserver will log the timestamp and action taken for any file change in the directory, including file creation, modification, and deletion.

You can also customize the log format and destination by providing a custom implementation of the TimestampObserver.