Java FileAlterationObserver-class And Method Code Example

Here is an example of using the FileAlterationObserver class from the Apache Commons IO library in Java to monitor a directory for changes and perform an action when a file is created or modified:



public class FileMonitorExample {
    public static void main(String[] args) {
        // specify the directory to monitor
        File directory = new File("/path/to/directory");
        // create a new observer
        FileAlterationObserver observer = new FileAlterationObserver(directory);
        // add a listener to respond to changes
        observer.addListener(new FileAlterationListenerExample());
        // start the observer

In this example, the FileAlterationObserver is set to monitor the specified directory, and a listener is added to respond to changes in the directory. The observer is then started to begin monitoring the directory. The FileAlterationListenerExample class that is being added as a listener, should implement the FileAlterationListener interface, which contains the following methods:

onStart(final FileAlterationObserver observer)
onDirectoryCreate(final File directory)
onDirectoryChange(final File directory)
onDirectoryDelete(final File directory)
onFileCreate(final File file)
onFileChange(final File file)
onFileDelete(final File file)
onStop(final FileAlterationObserver observer)

You can then implement the methods you need to perform the action you want to perform when a file is created, modified, or deleted.