2

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
      }
}
}
Community
  • 1
  • 1
clD
  • 2,523
  • 2
  • 22
  • 38
  • What problems does it cause? You can poll the directory manually but that comes with its own set of problems. Or you can just use the `ChangeEventHandler` to record which files need loading and do the loading later, so multiple events relating to a single file will only result in one load. – biziclop Jul 04 '14 at 18:02
  • use Apache Camel or Spring Integration – Neil McGuigan Jul 04 '14 at 18:51

1 Answers1

4

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).

user3465651
  • 706
  • 1
  • 4
  • 22