我有下面的代码来跟踪专用文件夹上的文件更改
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 循环并休眠以重新检查)
请问是怎么回事??