2

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

 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)并且程序运行时:

长尺寸 = Files.size(newFilePath) / (1000 * 1000);

它抛出

java.nio.file.NoSuchFileException: newfile.dat

和变量

writable

always= false (即使我尝试将其放入 While 循环并休眠以重新检查)

请问是怎么回事??

4

1 回答 1

0

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

我通过使用来解决

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

fullPath是文件的正确路径

但我想知道,这太废话了:( :(

于 2012-06-11T04:08:01.090 回答