功能彙總java
文件監聽實現原理
觀察者模式:將要監聽的目錄和感興趣的事件進行註冊,啓動專門的線程定時輪詢,檢查是否有感興趣事件發生,當有感興趣事件發生時調用相應觀察者的回調函數便可。apache
文件監聽代碼示例
ide
import java.io.File;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
/**
* 類描述:監聽文件變化示例
**/
public class FileMonitorTest { public static void main(String[] args) throws Exception { FileAlterationMonitor fileMonitor = new FileAlterationMonitor(1000); //設置文件過濾條件 IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), FileFilterUtils.nameFileFilter("mvn.txt")); FileAlterationObserver obs = new FileAlterationObserver(new File("D:/zk"), fileFilter); obs.addListener(new FileAlterationListenerAdaptor(){ @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()); } }); fileMonitor.addObserver(obs); fileMonitor.start(); } }