繁体   English   中英

WatchService监视特定目录以创建文件

[英]WatchService watch specfic directory for creation of files

public static void main (String args[]) throws Exception {
        Path _directotyToWatch = Paths.get(args[0]);
        WatchService watcherSvc = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = _directotyToWatch.register(watcherSvc, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        while (true) {
            watchKey=watcherSvc.take();
            for (WatchEvent<?> event: watchKey.pollEvents()) {
                WatchEvent<Path> watchEvent = castEvent(event);
                System.out.println(event.kind().name().toString() + " " + _directotyToWatch.resolve(watchEvent.context()));
                watchKey.reset();
            }
        }
    }

在上面的示例中,监视目录路径来自控制台参数。 我想静态传递目录路径。

尝试过此Paths.get(“ O:\\\\ test”); 但是抛出异常

Exception in thread "main" java.lang.NoClassDefFoundError: java/nio/file/Paths
    at JSR203_NIO2_WatchFolder.main(JSR203_NIO2_WatchFolder.java:40)
Caused by: java.lang.ClassNotFoundException: java.nio.file.Paths
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)

我只是遇到了这个问题,我想你想要的是:

Path path = FileSystems.getDefault().getPath(path_string);

尝试

Path _directotyToWatch = Paths.get("O:/test"); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM