我设法以我想要的方式写入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();}
答案 0 :(得分:1)
您必须清空FileOutputStream
。
FileOutputStream outStream = new FileOutputStream("src/virtualagenda/Reminders.xml");
XMLSerializer serializer = new XMLSerializer(outStream, outFormat);
serializer.serialize(xmlDoc);
outStream.flush()
或者如果您已完成流,只需使用outStream.close()
答案 1 :(得分:1)
怎么样:
outStream.flush();
outStream.close();
迫使写作?