我面临的问题是我希望TableView在XML文件更新后刷新。当数据被修改后,TableView会立即更新,并且当用户退出并重新打开应用程序时,新数据将按原样存在。但是我希望此更新是“自动的”,以便如果2个用户之一进行更改,其他用户的运行应用程序也将自动反映该更改。
我想定期读取XML文件,但是我没有运气。我正在使用DOM读取文件。我尚未查看ScheduledService,但这似乎是一个潜在的解决方案。 我还添加了一个“刷新数据”按钮,该按钮调用了我在XML文件中读取的位置的类,但这也不起作用。有提示吗?
答案 0 :(得分:1)
您可以使用WatchService API来监视文件夹。每当添加,删除或修改文件时,这都可以触发事件。
这里是演示的快速MCVE。在此示例中,我们仅关注对现有文件的修改:
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
public class Main {
public static void main(String[] args) {
// Launch the watcher in a background thread
new Thread(() -> {
try {
setupWatcher();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}).start();
}
public static void setupWatcher() throws IOException, InterruptedException {
System.out.println("Listening for changes to DATA.XML");
// Set the directory we want to watch for changes
Path dir = Paths.get("your/path");
// Create the WatchService
WatchService watchService = FileSystems.getDefault().newWatchService();
// Only watch for modifications (ignore new or deleted files)
dir.register(watchService, ENTRY_MODIFY);
// The WatchKey will collect any events from the WatchService. We want this to run indefinitely so we wrap in
// an infinite loop
while (true) {
// Gets the latest event
WatchKey watchKey = watchService.take();
// When a change is found, let's find out what kind and act appropriately
if (watchKey != null) {
// For each event triggered
watchKey.pollEvents().forEach(watchEvent -> {
// Get the filename of the file that was modified
String filename = watchEvent.context().toString();
// If it is the file we care about, do something
if (filename.equalsIgnoreCase("DATA.XML")) {
// Do your update of the TableView here
System.out.println("DATA.XML has been changed!");
}
});
// After the event was processed, reset the watchKey
watchKey.reset();
}
}
}
}
其他信息可以在JavaDocs或this tutorial中找到。
答案 1 :(得分:-1)
您可能希望使用Java WatchService在文件内容更改时收到通知。参见Oracle docs
这里也是显示如何使用它的tutorial。