我设法以所需的方式写入xml文件,但是它只会在程序退出后才更新文件。我希望在按下按钮后立即更新文件。
这是我正在使用的代码。单击JButton即可运行。
try {
documentFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentFactory.newDocumentBuilder();
xmlDoc = documentBuilder.parse(Reminders.class.getResourceAsStream("Reminders.xml"));
} catch(ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
Node rNode = xmlDoc.getChildNodes().item(0);
Node remindersNode = xmlDoc.getElementsByTagName("reminders").item(0);
Node newReminder = xmlDoc.createElement("r" + remindersNode.getChildNodes().getLength()/2);
// Elements are created and put together
// Redacted because they take up too much space
OutputFormat outFormat = new OutputFormat(xmlDoc);
outFormat.setIndenting(true);
try {
FileOutputStream outStream = new FileOutputStream("src/virtualagenda/Reminders.xml");
XMLSerializer serializer = new XMLSerializer(outStream, outFormat);
serializer.serialize(xmlDoc);
outStream.flush();
outStream.close();
}catch(IOException e) {e.printStackTrace();}
最佳答案
怎么样:
outStream.flush();
outStream.close();
强迫写作?