WatchService Api file watching throws exception when try access file in created event occur

梦想的初衷 提交于 2019-12-11 01:08:30

问题


i have code below to tracking file changes on a dedicate folder

 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();

            }
        }
    }

But when have a file (named=newfile.dat) created and program hit the line:

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

it throws

java.nio.file.NoSuchFileException: newfile.dat

and variable

writable

always= false (even if i try put it to While loop and sleep to recheck)

Please tell what happened ??


回答1:


i find out that the variable newFilePath is always relative path :( :(

i work around by use

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

fullPath is correctly path of the file

but i wonder, it 's too crap code :( :(



来源:https://stackoverflow.com/questions/10974120/watchservice-api-file-watching-throws-exception-when-try-access-file-in-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!