【问题标题】:WatchService Api file watching throws exception when try access file in created event occurWatchService Api 文件监视在创建事件中尝试访问文件时抛出异常
【发布时间】:2012-06-11 02:58:42
【问题描述】:

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

 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 循环并休眠以重新检查)

请说说发生了什么??

【问题讨论】:

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


    【解决方案1】:

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

    我通过使用来解决问题

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

    fullPath 是正确的文件路径

    但我想知道,它的代码太垃圾了 :( :(

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2021-03-04
      相关资源
      最近更新 更多