WatchService监视用于创建文件的特定目录

时间:2012-01-12 05:22:57

标签: java java-ee

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)

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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