Thursday, August 13, 2015
Observe folder to pick file when it's available
public class MMTServerStartListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
YourMonitorListenerImpl fileMonitor;
@Override
public void onApplicationEvent(ContextRefreshedEvent context) {
try {
String filePath = "<file path>";
startMonitor(filePath, fileMonitor);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
private void startMonitor(String filePath, YourMonitorListenerImpl fileMonitorImpl) {
try {
if (filePath != null && filePath.length() > 0) {
final File directory = new File(filePath.trim());
FileAlterationObserver fao = new FileAlterationObserver(directory);
fao.addListener(fileMonitorImpl);
final FileAlterationMonitor monitor = new FileAlterationMonitor();
monitor.addObserver(fao);
LOGGER.info("Starting monitor. CTRL+C to stop.");
monitor.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
LOGGER.info("Stopping monitor.");
monitor.stop();
} catch (Exception ignored) {
LOGGER.error(ignored.getMessage(), ignored);
}
}
}));
} else {
LOGGER.error("Invalid input the monitor folder");
}
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
}
With "YourMonitorListenerImpl" implements "FileAlterationListener" interface.
Labels:
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment