OnlyPatil
OnlyPatil

Reputation: 1

How to prevent an XML file content to be modified if exception is thrown

I have an XML file with some content. I want to modify this file on a REST request. While creating a new FileOutputStream, all content is erased and later with my code, I can add desired data into the XML file. But after creating a new FileOutputStream, IF EXCEPTION IS THROWN, all the content is erased.

How to retain the original content from XML file(Abc.xml) as it is if exception is thrown?

FileOutputStream fileOutputStream = null;
    try {
        validateXMLSchema("Abc.xsd", "Abc.xml");
        JAXBContext jc = JAXBContext.newInstance(Structure.class);
        Marshaller marshaller = jc.createMarshaller();
        fileOutputStream = new FileOutputStream(
            new File(System.getProperty("rootPath") + "/WEB-INF/classes"
                + "/" + "Abc.xml"));
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        Structure structure = new Structure();
        structure.setName("Types");
        ObjectFactory objectFactory = new ObjectFactory();

} catch (JAXBException e) {
        throw IlmODataExceptionBuilder.buildODataApplicationException(
            FILE_FORMAT_IS_INCORRECT_CREATE_FILE_AGAIN,
            HttpStatusCode.BAD_REQUEST, "Abc.xml");
    } catch (FileNotFoundException e) {
        throw IlmODataExceptionBuilder.buildODataApplicationException(
            FILE_NOT_FOUND, HttpStatusCode.BAD_REQUEST,
            "Abc.xml");
    } finally {
        if (fileOutputStream != null) {
        fileOutputStream.close();
        }
    }

Here method validateXMLSchema() just validates the XML schema. Any help is appreciated.

Upvotes: 0

Views: 42

Answers (2)

jtahlborn
jtahlborn

Reputation: 53694

A good way to handle something like this is to rely on the generally atomic-ish file rename operation.

  1. create a temp file
  2. write the output to the temp file
  3. if the temp file write completes successfully, rename it to the "real" file name
  4. if the temp file write fails, delete the temp file

Upvotes: 1

kumesana
kumesana

Reputation: 2490

By not creating any kind of FileOutputStream nor similar, before you've done the work that may potentially fail with an Exception.

Creating a FileOutputStream prepares the filesystem to receive the file's bytes, by creating the file. And if it existed already, it will erase the existing file instead of just creating it.

So, don't do that before you're ready to erase the file.

Upvotes: 0

Related Questions