简体   繁体   中英

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

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 ??

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 :( :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM