Java高效監控文件目錄


有三種方式:
1、java common.io    內部實現是遍歷的方式,小文件夾的效率還好,比如我測試60G的目錄,就很慢很慢了。
2、jdk 7 的watch service    //經測試基本不可用。在一個40g的很深的目錄下去新建和刪除文件5分鍾都沒結果。主要原因是需要對每一個Path進行注冊監控。
3、jnotify                   直接調用windows的api,效率很高,也很簡單,推薦使用。

------------------------------------------------------------------------------------------------------------------------------------------------------------
common.io
需要java.io 2.1及其以上版本。版本地址如下:
http://commons.apache.org/io/download_io.cgi

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
 
/**  
 * 自定義文件監聽器  
 * @author    
 * @date    2010-11-16  
 * @file    org.demo.file.MyFileListener.java  
 */  
public class MyFileListener extends FileAlterationListenerAdaptor{   
    @Override  
    public void onFileCreate(File file) {   
        System.out.println("[新建]:" + file.getAbsolutePath());   
    }   
    @Override  
    public void onFileChange(File file) {   
        System.out.println("[修改]:" + file.getAbsolutePath());   
    }   
    @Override  
    public void onFileDelete(File file) {   
        System.out.println("[刪除]:" + file.getAbsolutePath());   
    }   
}


import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;


public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
           // 監控目錄  
        String rootDir = "d:\\Temp";  
        // 輪詢間隔 5 毫秒  
        long interval = 5l;  
        //   
        FileAlterationObserver observer = new FileAlterationObserver(  
                                              rootDir,null,   
                                              null);  
        observer.addListener(new MyFileListener());  
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer);  
        // 開始監控  
        monitor.start(); 
    }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------
jdk7 watchservice
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;

public class TestWatchService {

    public static void main(String[] args) throws Exception {
        final FileSystem fileSystem = FileSystems.getDefault();
        try (final WatchService watchService = fileSystem.newWatchService()) {
            final Map<WatchKey, Path> keyMap = new HashMap<WatchKey, Path>();
            final Path path = Paths.get("F:\\Test");
            keyMap.put(path.register(watchService, ENTRY_CREATE, ENTRY_DELETE),path);
            WatchKey watchKey;
            do {
                watchKey = watchService.take();
                final Path eventDir = keyMap.get(watchKey);
                for (final WatchEvent<?> event : watchKey.pollEvents()) {
                    final WatchEvent.Kind kind = event.kind();
                    final Path eventPath = (Path) event.context();
                    System.out.println(eventDir + ": " + event.kind() + ": " + event.context());
                }
            } while (watchKey.reset());
        }
    }

}

 
------------------------------------------------------------------------------------------------------------------------------------------------------------
jnotify
詳見 http://www.blogjava.net/pengo/archive/2011/01/09/342622.html
jnotify分為64位 和 32位。 詳見 http://jnotify.sourceforge.net/
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
           // 監控目錄  
        String rootDir = "Z:\\";
        String path = rootDir;
        int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED
                | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
        boolean watchSubtree = true;
        while (true) { //否則一次就完了
            System.out.println("begin watch");
            JNotify.addWatch(path, mask, watchSubtree, new MyJnotifyListner());
            Thread.sleep(10000);
            System.out.println("end watch");
        }
    }

}



import net.contentobjects.jnotify.JNotifyListener;


public class MyJnotifyListner implements JNotifyListener {
    public void fileRenamed(int wd, String rootPath, String oldName,
            String newName) {
        System.out.println("文件:" + rootPath + " : " + oldName + " 重命名為: "
                + newName + "\n");
    }

    public void fileModified(int wd, String rootPath, String name) {
        System.out.println("文件修改 " + rootPath + " : " + name + "\n");
    }

    public void fileDeleted(int wd, String rootPath, String name) {
        System.out.println("刪除文件: " + rootPath + " : " + name + "\n");
    }

    public void fileCreated(int wd, String rootPath, String name) {
        System.out.println("新建文件: " + rootPath + " : " + name + "\n");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM