Search code examples
javadatabaseshared-directory

Monitor a shared folder for changes and pull to database


I have a folder which user save or modify files in. When a file is created or modified I need to serialise that file and insert into a database.

I have looked at Java Watch Directory and Apache commons.io.monitor. The watch directory approach picks up every event because it is tied to the native file event notification which causes a problem. Stackoverflow question multiple events watch directory

What is the best way/or any other approaches to monitor the directory?

import org.apache.commons.io.monitor.*;
import java.io.*;

public class ApacheWatch2 {

public static void startApacheWatch(String path) {
    final File folder = new File(path);
    if (folder.exists()) {
        try {
            FileAlterationObserver observer = new FileAlterationObserver(folder);
            observer.addListener(new ChangeEventHandler());
            final FileAlterationMonitor monitor = new FileAlterationMonitor();
            monitor.addObserver(observer);
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    } else {
        throw new RuntimeException("File does not exist");
    }
}

private static class ChangeEventHandler extends FileAlterationListenerAdaptor {

    @Override
    public void onFileCreate(File file) {
        //DO SERIALISATION STUFF WITH FILE
    }

    @Override
    public void onFileChange(File file) {
        //DO SERIALISATION STUFF WITH FILE
      }
}
}

Solution

  • I'd recommend having a look @ spring batch http://projects.spring.io/spring-batch It does cater for polling directories, scheduling and writers for db interaction(as well as a host of other features).