欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

Java中监控文件变化的多种方案

一、使用Apache.Common.io库

package com.test.utils.files;

import com.sun.deploy.util.SyncFileAccess;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

public class FolderWatcher extends FileAlterationListenerAdaptor {
    FileAlterationMonitor monitor;

    public FolderWatcher(String directory) {
        monitor = new FileAlterationMonitor(500);
        FileAlterationObserver fileObserver = new FileAlterationObserver(directory);
        fileObserver.addListener(this);
        monitor.addObserver(fileObserver);
    }

    public void start(boolean isDaemonThread) throws Exception {
        if (isDaemonThread) {
            monitor.setThreadFactory(r -> {
                Thread th = new Thread(r);
                th.setDaemon(true);
                return th;
            });
        }
        monitor.start();
    }

    @Override
    public void onFileChange(File file) {
        System.out.println("change" + file);
    }

    @Override
    public void onFileCreate(File file) {
        while (true) {
            try {
                SyncFileAccess fileAccess = new SyncFileAccess(file);
                SyncFileAccess.FileInputStreamLock lock = fileAccess.openLockFileInputStream(1000, false);lock.getFileInputStream().close();
          lock.release();
          
break;
        }
catch (Exception e)
       {
try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } System.out.println("create:" + file); } }

二、使用JAVA.NIO的

package com.test.utils.files;

import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.*;

public class FolderWatcher2 {
    private WatchService watcher;

    public FolderWatcher2(String directory) throws IOException {
        watcher = FileSystems.getDefault().newWatchService();
        Path path = Paths.get(directory);
        path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
        Path path1 = Paths.get(directory, "abc");
        path1.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
    }
    public void start() throws InterruptedException {
        while (true) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {//事件可能lost or discarded
                    continue;
                }

                Path fileName = (Path) event.context();
                System.out.printf("Event %s has happened,which fileName is %s%n", kind.name(), fileName);
            }
            //这行必须有,不然不能连续地监控目录
            if (!key.reset()) {
                break;
            }
        }
    }

}

 

 
posted @ 2018-04-27 11:21  宋兴柱  阅读(5277)  评论(0编辑  收藏  举报