我一般都是非常新的Java世界。我有一个javafx应用程序,我正在尝试在log4j日志文件上设置文件观察器以监视更改并显示textarea中的更改。我有以下代码,它可以在log4j日志文件以外的任何文件上正常工作。
另外,我注意到当我在Windows资源管理器中刷新包含log4j文件的文件夹时,它似乎工作。我很困惑,不知道我做错了什么或不确定这是否可行。
请告知。
package application;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.text.TextFlow;
public class MainappWindowController implements Initializable {
@FXML
private Button btn_appendtext;
@FXML
private TextArea txtarea_logview;
@FXML
private TextFlow txtflow_logview;
// FOR Logging
public static final Logger log = Logger.getLogger(Main.class);
String log4jConfPath = "./log4j_properties/log4j.properties";
Path watchPath = Paths.get("C:/temp/mylogfile_being_watched_by_java.txt");
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
btn_appendtext.setOnAction(e -> {
testlogger();
});
// load file initially
if (Files.exists(watchPath)) {
loadFile();
} else {
log.info("File does not exist");
}
// watch file
WatchThread watchThread = new WatchThread(watchPath);
watchThread.setDaemon(true);
watchThread.start();
// Add log4j properties file to configuration
PropertyConfigurator.configure(log4jConfPath);
}
public void testlogger() {
log.info("This is an information message");
}
private void loadFile() {
try {
String stringFromFile = Files.lines(watchPath).collect(Collectors.joining("\n"));
txtarea_logview.setText(stringFromFile);
} catch (Exception e) {
e.printStackTrace();
}
}
private class WatchThread extends Thread {
Path watchPath;
public WatchThread(Path watchPath) {
this.watchPath = watchPath;
}
@Override
public void run() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key = watchPath.getParent().register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
// wait for key to be signaled
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path path = ev.context();
if (!path.getFileName().equals(watchPath.getFileName())) {
continue;
}
// process file
Platform.runLater(() -> {
loadFile();
});
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException x) {
System.err.println(x);
}
}
}
}