我使用Apache log4j记录器记录我的应用程序。这是记录器配置的重要部分:
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="c:/data/logfile.txt" />
<param name="BufferedIO" value="false" />
<param name="BufferSize" value="1" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="30MB" />
<param name="MaxBackupIndex" value="1" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
</layout>
</appender>
我观看文件更改的班级是这样的:
public static class FileWatcher {
private Thread thread;
private WatchService watchService;
public void start(final Path file) throws IOException {
watchService = FileSystems.getDefault().newWatchService();
Path parent = file.getParent();
parent.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
System.out.println("Going to watch " + file);
thread = new Thread(() -> {
while (true) {
WatchKey wk = null;
try {
wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
Path changed = parent.resolve((Path) event.context());
if (Files.exists(changed) && Files.isSameFile(changed, file)) {
System.out.println("File change event: " + changed);
break;
}
}
} catch (InterruptedException e) {
System.out.println("Ending my watch");
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
System.out.println("Error while reloading cert");
} finally {
if (wk != null) {
wk.reset();
}
}
}
});
thread.start();
}
public void stop() {
thread.interrupt();
try {
watchService.close();
} catch (IOException e) {
System.out.println("Error closing watch service");
}
}
}
实例化是这样的
FileWatcher watcher = new FileWatcher();
try {
watcher.start(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
}
通常一切都按预期工作,但是唯一的事情是,当我使用外部编辑器或通过以下方式打开(已更改)文件时,WatchService仅对更改后的文件做出反应:
File f = new File(path);
StringBuilder builder = readFile(f);
该应用程序当前在Windows 10上运行。 那么,为什么WatchService不能对文件更改立即做出反应?