WatchService Api文件监视在创建事件中尝试访问文件时抛出异常

时间:2012-06-11 02:58:42

标签: java filesystemwatcher java-7 java.nio.file

我有以下代码来跟踪专用文件夹上的文件更改

 Path path = Paths.get("f:\\logs");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    WatchKey key = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

    while (true) {
        final WatchKey watchKey = watchService.take();
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            WatchEvent.Kind<?> kind = watchEvent.kind();
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                WatchEvent<Path> eventPath = (WatchEvent<Path>) watchEvent;
                Path newFilePath = eventPath.context();
                boolean writable = false;
                System.out.println(writable);
                long size = Files.size(newFilePath) / (1000 * 1000);

                System.out.println(newFilePath.toAbsolutePath() + "wriable:" + writable + "size:" + size);
                watchKey.reset();

            }
        }
    }

但是当创建了一个文件(named = newfile.dat)并且程序命中时:

  

long size = Files.size(newFilePath)/(1000 * 1000);

它抛出

  

java.nio.file.NoSuchFileException:newfile.dat

和变量

writable

总是=假(即使我尝试将它放入While循环并睡眠以重新检查)

请告诉我发生了什么?

1 个答案:

答案 0 :(得分:0)

我发现变量newFilePath总是相对路径:( :(

我通过使用

来解决
Path dir = (Path) watchKey.watchable();
Path fullPath = dir.resolve(newFilePath);

fullPath是文件的正确路径

但我想知道,这是废话代码:( :(