监控类
package com.sjj.advance.thirdlibrary.commons_io.filelistener;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileListener implements FileAlterationListener {
@Override
public void onStart(FileAlterationObserver fileAlterationObserver) {
System.out.println("onStart");
}
@Override
public void onDirectoryCreate(File file) {
System.out.println("onDirectoryCreate:" + file.getName());
}
@Override
public void onDirectoryChange(File file) {
System.out.println("onDirectoryChange:" + file.getName());
}
@Override
public void onDirectoryDelete(File file) {
System.out.println("onDirectoryDelete:" + file.getName());
}
@Override
public void onFileCreate(File file) {
System.out.println("onFileCreate:" + file.getName());
}
@Override
public void onFileChange(File file) {
System.out.println("onFileChange : " + file.getName());
}
@Override
public void onFileDelete(File file) {
System.out.println("onFileDelete :" + file.getName());
}
@Override
public void onStop(FileAlterationObserver fileAlterationObserver) {
System.out.println("onStop");
}
}
测试类
package com.sjj.advance.thirdlibrary.commons_io.filelistener;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class Test {
FileAlterationMonitor monitor = null;
public Test(long interval) {
monitor = new FileAlterationMonitor(interval);
}
/**
* 给文件添加监听
* @param path
* @param listener
*/
public void monitor(String path, FileAlterationListener listener) {
FileAlterationObserver observer = new FileAlterationObserver(new File(path));
monitor.addObserver(observer);
observer.addListener(listener);
}
public void stop() throws Exception {
monitor.stop();
}
public void start() throws Exception {
monitor.start();
}
public static void main(String[] args) throws Exception {
//初始化监听
Test m = new Test(1000);//设置监控的间隔时间
//指定文件夹,添加监听
m.monitor("E:\\data\\commoms-io", new FileListener());
//开启监听
m.start();
}
}