问题
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