Question

I'm trying to write some XML lines in a XML file. However, I can only do it if the file doesn't exist, because if it exists I'll overwrite the information.

Here's my code:

public void writeToXMLSimulation() throws IOException {
    File f = new File("Simulation_" + pt.ipp.isep.gecad.masgrip.MASGriP_GUI.getContainerNameTxt().getText() + "_Details.xml");
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter xmlWriter = null;
    if (!f.exists()) {

        try {
            xmlWriter = new XMLWriter(new OutputStreamWriter(
                    new FileOutputStream(f), "UTF8"),
                    format);
            xmlWriter.write(configs.XMLwriterDOM4J.createXMLDocumentForSimulations(jLabelAL, jTextFieldAL, id));
        } finally {
            if (xmlWriter != null) {
                xmlWriter.flush();
                xmlWriter.close();
            }
        }

    } else {

        try {
            //I NEED SOMETHING HERE TO GET ME TO THE LAST LINE OF FILE

    xmlWriter.write(
configs.XMLwriterDOM4J.createXMLDocumentForSimulations(
jLabelAL, jTextFieldAL, id));
            } finally {
                if (xmlWriter != null) {
                    xmlWriter.flush();
                    xmlWriter.close();
                }
            }

        }

    }

What can I do, to make my code write after the last line? (without overwritting)

Thanks

Was it helpful?

Solution

In the general case, you can write to a file in append mode using:

new FileOutputStream(file, true);

The second parameter is a boolean with true meaning append and false meaning overwrite. The default is false (as you have no doubt discovered).

That being said, appending data to the end of an XML file probably does not make sense. It would be much better to use an XML reader to read the XML file into a Document object, add elements to that object, and then write that object back to disk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top