简体   繁体   中英

How to write to an xml file while the program in running?

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();}

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()

How about:

outStream.flush();
outStream.close();

to force the writing?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM