Reputation: 1
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
Reputation: 53694
A good way to handle something like this is to rely on the generally atomic-ish file rename operation.
Upvotes: 1
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