我创建了一个类FolderObserver,它在我的项目中观察一个文件夹以进行更改(文件创建/文件删除)。我的类正在实现Runnable接口(我使用了来自apache commons的FileAlterationObserver,FileAlterationMonitor,FileAlterationListener类)。
在我的主类中,我以FolderObserver对象作为参数启动一个线程。 我想知道的是,我如何通知我的线程已发生的变化?例如,在我的文件夹中创建了一个新文件。
这是我的类FolderObserver:
public class FolderObserver implements Runnable {
private final String DIR = "server/scripts/gremlin-groovy/calculations/";
final long pollingInterval = 5000L;
private File folder;
private FileAlterationObserver observer;
private FileAlterationMonitor monitor;
private FileAlterationListener listener;
public FolderObserver()
{
System.out.println("Creating Runnable");
folder = new File(DIR);
observer = new FileAlterationObserver(folder);
monitor = new FileAlterationMonitor(pollingInterval);
}
@Override
public void run() {
System.out.println("Thread is running");
listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
@Override
public void onFileCreate(File file) {
try {
// "file" is the reference to the newly created file
System.out.println("Created file : " + file.getCanonicalPath());
} catch (IOException e) {
}
}
// Is triggered when a file is deleted from the monitored folder
@Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("Removed file : " + file.getCanonicalPath());
//logger.log(LogLevel.DEBUG,logId,"File exists in location '{}'",bool);
} catch (IOException e) {
//logger.log(LogLevel.ERROR, "Received IOException '{}' when trying to remove file", e.toString());
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
try {
monitor.start();
System.out.println("Monitor started");
//logger.log(LogLevel.DEBUG,logId,"Monitor started");
} catch (Exception e) {
//logger.log(LogLevel.ERROR, "Received Exception '{}' when trying to start monitor", e.toString());
}
}
}
这是我从主类创建和启动线程的方法:
FolderObserver observer = new FolderObserver();
Thread t = new Thread(observer);
t.start();
答案 0 :(得分:0)
您在FolderObserver
内创建了一个内部界面。
public interface MyTrueObserver(){
public void notifySmthChanged();
}
现在,您可以通过执行
在主类中实现该类public class MyMainClass implements MyTrueObserver()
您可以定义界面方法
public void notifySmthChanged(){
// I got called Do smth!
}
最后,您引用主要类的线程。
并在此处致电
@Override
public void onFileCreate(File file) {
referenceObjectToMainClass.notifySmthChanged();
}