我有一个文件夹,用户在其中保存或修改文件。创建或修改文件时,我需要序列化该文件并插入到数据库中。
我看过Java目录和Apache commons.io.monitor。watch目录方法接收每个事件,因为它与本机文件事件通知绑定在一起,从而导致问题。Stackoverflow question multiple events watch 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
}
}
}发布于 2014-07-04 18:01:27
我建议您看一看@ spring http://projects.spring.io/spring-batch,它确实适合轮询目录、数据库交互的调度和编写器(以及许多其他特性)。
https://stackoverflow.com/questions/24578950
复制相似问题