Reputation: 327
I've managed to write to an xml file in the way that I want, but it will only update the file after the program is exited. I'd like for the file to update as soon as a button is pressed.
Here is the code I'm using. It's run when a JButton is clicked on.
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();}
Upvotes: 0
Views: 45
Reputation: 11381
You have to flush the FileOutputStream
.
FileOutputStream outStream = new FileOutputStream("src/virtualagenda/Reminders.xml");
XMLSerializer serializer = new XMLSerializer(outStream, outFormat);
serializer.serialize(xmlDoc);
outStream.flush()
Or if you are done with the stream, just close it using outStream.close()
Upvotes: 1
Reputation: 1840
How about:
outStream.flush();
outStream.close();
to force the writing?
Upvotes: 1