Java 如何将WatchService转换为可运行的?

Java 如何将WatchService转换为可运行的?,java,nio,runnable,Java,Nio,Runnable,我有一个监视服务,它监视目录中的ENTRY\u DELETE、ENTRY\u CREATE和ENTRY\u MODIFY事件,并根据事件执行逻辑 我需要服务监视目录中的所有更改,而不是退出循环。但我也需要进入我的另一个逻辑 如何将这些方法重构为可运行的 下面如果是代码 public static void main(String[] args) { System.out.println("Started watching"); FileServices fileS

我有一个监视服务,它监视目录中的
ENTRY\u DELETE
ENTRY\u CREATE
ENTRY\u MODIFY
事件,并根据事件执行逻辑

我需要服务监视目录中的所有更改,而不是退出循环。但我也需要进入我的另一个逻辑

如何将这些方法重构为
可运行的

下面如果是代码

public static void main(String[] args) {        
    System.out.println("Started watching");
    FileServices fileServices = new FileServicesImpl();

    fileServices.setSrcDir(fileServices.getValue("srcdir","properties/abc.properties"));
    fileServices.setDestDir(fileServices.getValue("destdir","properties/abc.properties"));

    System.out.println(fileServices.getSrcDir());
    System.out.println(fileServices.getDestDir());

    Map<String,WatchEvent> files = new HashMap<>();
    MappingConsole mappingConsole = new MappingConsole();

    for(;;){
        files = fileServices.getEventMap();
        for(String f : files.keySet()){
            System.out.println("Size of files: "+files.size());
            if (files.get(f).kind() == ENTRY_CREATE || files.get(f).kind() == ENTRY_MODIFY) {
                System.out.println("Processing: " +f);
                mappingConsole.map940(fileServices.getSrcDir(),f,fileServices.getDestDir());
                System.out.println("Processed: " +f);
            }
        }
    }

}
publicstaticvoidmain(字符串[]args){
System.out.println(“开始监视”);
FileServices FileServices=newfileservicesimpl();
fileServices.setSrcDir(fileServices.getValue(“srcdir”,“properties/abc.properties”);
fileServices.setDestDir(fileServices.getValue(“destdir”,“properties/abc.properties”);
System.out.println(fileServices.getSrcDir());
System.out.println(fileServices.getDestDir());
映射文件=新的HashMap();
MappingConsole MappingConsole=新建MappingConsole();
对于(;;){
files=fileServices.getEventMap();
for(字符串f:files.keySet()){
System.out.println(“文件大小:+files.Size());
if(files.get(f).kind()==条目| | files.get(f).kind()==条目|修改){
System.out.println(“处理:+f”);
mappingConsole.map940(fileServices.getSrcDir(),f,fileServices.getDestDir());
系统输出打印项次(“已处理:+f);
}
}
}
}
从FileServicesImpl:

@Override
public void monitorSrcDir(String srcDir){
    for(;;){
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path myDir = Paths.get(srcDir);
            WatchService watcher = myDir.getFileSystem().newWatchService();
            myDir.register(watcher, ENTRY_CREATE,ENTRY_DELETE, ENTRY_MODIFY);
            WatchKey watchKey = watcher.take();
            List<WatchEvent<?>> events = watchKey.pollEvents();
            for (WatchEvent event : events) {
                if (event.kind() == ENTRY_CREATE) {
                    System.out.println("Create: " + event.context().toString());
                    getEventMap().put(event.context().toString(), event);
                }
                if (event.kind() == ENTRY_DELETE) {
                    System.out.println("Delete: " + event.context().toString());
                    getEventMap().put(event.context().toString(), event);
                }
                if (event.kind() == ENTRY_MODIFY) {
                    System.out.println("Modify: " + event.context().toString());
                    getEventMap().put(event.context().toString(), event);
                }
            }
            watchKey.reset();
        }  catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
@覆盖
公共void监视器srcDir(字符串srcDir){
对于(;;){
试一试{
WatchService WatchService=FileSystems.getDefault().newWatchService();
Path myDir=Path.get(srcDir);
WatchService watcher=myDir.getFileSystem().newWatchService();
myDir.register(观察者、条目创建、条目删除、条目修改);
WatchKey WatchKey=watcher.take();
列表我这样做:

public class WatchServiceMonitor implements Monitor, Runnable, Closeable {
    private static Logger log = LoggerFactory.getLogger( WatchServiceMonitor.class.getName() );
    private Destination destination;
    private Path hotFolder;
    private Thread thread;

    public WatchServiceMonitor( Path hotFolder, Destination destination ) {
        this.hotFolder = hotFolder;
        this.destination = destination;

    }

    @Override
    public void close() throws IOException {
        try {
            stop();
        }
        catch ( InterruptedException e ) {
            log.warn( "request to stop failed, guess its time to stop being polite!" );
        }
    }

    @Override
    public void join() throws InterruptedException {
        thread.join();
    }

    @Override
    public void run() {
        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            if ( log.isTraceEnabled() ) log.trace( "registering create watcher on " + hotFolder.toAbsolutePath().toString() );
            hotFolder.register( watcher, StandardWatchEventKinds.ENTRY_CREATE );
            if ( log.isDebugEnabled() ) log.debug( "watcher registration complete for " + hotFolder.toAbsolutePath().toString() );
            synchronized ( this ) {
                this.notifyAll();
            }
            for ( ;; ) {
                if ( thread.isInterrupted() ) break;

                WatchKey key = null;
                try {
                    log.trace( "waiting for create event" );
                    key = watcher.take();
                    log.trace( "got an event, process it" );
                }
                catch ( InterruptedException ie ) {
                    log.trace( "interruped, must be time to shut down..." );
                    break;
                }

                for ( WatchEvent<?> eventUnknown : key.pollEvents() ) {
                    WatchEvent.Kind<?> kind = eventUnknown.kind();

                    if ( kind == StandardWatchEventKinds.OVERFLOW ) return;

                    @SuppressWarnings( "unchecked" )
                    WatchEvent<Path> eventPath = (WatchEvent<Path>) eventUnknown;
                    Path path = hotFolder.resolve( eventPath.context() );
                    log.trace( "calling destination.transfer({})", path );
                    destination.transfer( path );
                    log.info( "transferred {} to destination" );

                    if (! key.reset()) {
                        break;
                    }
                }
            }
        }
        catch ( IOException ioe ) {
            log.error( ioe.getMessage(), ioe );
        }
        log.debug( "existing run loop" );
    }

    @Override
    public void start() throws InterruptedException {
        log.trace( "starting monitor" );
        thread = new Thread( this );
        thread.start();
        synchronized ( this ) {
            this.wait();
        }
        log.trace( "monitor started" );
    }

    @Override
    public void stop() throws InterruptedException {
        log.trace( "stopping monitor" );
        thread.interrupt();
        thread.join();
        thread = null;
        log.trace( "monitor stopped" );
    }
}
公共类WatchServiceMonitor实现了Monitor、Runnable和Closeable{
私有静态记录器log=LoggerFactory.getLogger(WatchServiceMonitor.class.getName());
私人目的地;
专用路径热文件夹;
私有线程;
公共WatchServiceMonitor(路径热文件夹,目标){
this.hotFolder=热文件夹;
this.destination=目的地;
}
@凌驾
public void close()引发IOException{
试一试{
停止();
}
捕捉(中断异常e){
log.warn(“停止请求失败,猜是时候停止礼貌了!”);
}
}
@凌驾
public void join()引发InterruptedException{
thread.join();
}
@凌驾
公开募捐{
try(WatchService watcher=FileSystems.getDefault().newWatchService()){
if(log.isTraceEnabled())log.trace(“在“+hotFolder.toabsolutionPath().toString()上注册创建观察程序”);
hotFolder.register(watcher、StandardWatchEventTypes.ENTRY\u CREATE);
if(log.isDebugEnabled())log.debug(“为“+hotFolder.toabsolutionPath().toString()完成监视程序注册”);
已同步(此){
this.notifyAll();
}
对于(;;){
如果(thread.isInterrupted())中断;
WatchKey=null;
试一试{
log.trace(“等待创建事件”);
key=watcher.take();
trace(“得到一个事件,处理它”);
}
捕获(中断异常ie){
trace(“已中断,必须是关闭时间…”);
打破
}
对于(WatchEvent eventUnknown:key.pollEvents()){
WatchEvent.Kind Kind=eventUnknown.Kind();
if(kind==StandardWatchEventKinds.OVERFLOW)返回;
@抑制警告(“未选中”)
WatchEvent eventPath=(WatchEvent)eventUnknown;
Path Path=hotFolder.resolve(eventPath.context());
log.trace(“调用目的地.transfer({})”,路径);
目的地。转移(路径);
log.info(“传输{}到目的地”);
如果(!key.reset()){
打破
}
}
}
}
捕获(ioe异常ioe){
log.error(ioe.getMessage(),ioe);
}
调试(“现有运行循环”);
}
@凌驾
public void start()引发InterruptedException{
日志跟踪(“启动监视器”);
线程=新线程(此);
thread.start();
已同步(此){
这个。等等();
}
log.trace(“监视器已启动”);
}
@凌驾
public void stop()引发InterruptedException{
日志跟踪(“停止监视器”);
thread.interrupt();
thread.join();
线程=null;
log.trace(“监视器停止”);
}
}
Destination
类是我自己的一个类,它知道如何从
WatchService
事件指示的路径进行传输


因此,本质上,我只是将整个
WatchService
循环包装在
Runnable
实例的
run
方法中。

从您的代码看,您正在做的事情与我正在做的非常相似。希望这能有所帮助。