Reputation: 3620
I apologize in advance as I lack knowledge of file system behavior.
I need to read a large XML file, modify it, and then write it out to the same file.
Here is my code to setup the XMLEventReader and XMLEventWriter:
XMLInputFactory xmlif = XMLInputFactory.newInstance();
InputStreamReader isr = new InputStreamReader(new FileInputStream(m_cPath.toString()),
StandardCharsets.UTF_8.name());
m_evtr = xmlif.createXMLEventReader(isr);
XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(m_cPath.toString()), StandardCharsets.UTF_8);
m_evtw = xmlof.createXMLEventWriter(osw);
m_evtf = XMLEventFactory.newInstance();
If I had an input such as:
<root>
<entry>1</entry>
<insert />
<entry>2</entry>
<entry>3</entry>
<entry>4</entry>
</root>
If I were to do something like the following, would it be safe?
try {
while(m_evtr.hasNext()) {
XMLEvent evt = m_evtr.nextEvent();
m_evtw.add(evt);
if( evt.isEndElement()) {
EndElement endElement = evt.asEndElement();
String localName = endElement.getName().getLocalPart();
if( localName.equals("insert") ) {
// create and write new entry elements following the insert element here
}
}
}
} finally {
isr.close();
osw.close();
m_evtr.close();
m_evtw.close();
}
It seems to work fine. But, I don't know if I should be creating a new file and then copying over the old one.
My concern is if it's safe to read and write to the same path this way. Especially since there will be content inserted, and then the read operations need to continue without seeing the newly added elements.
Upvotes: 0
Views: 192
Reputation: 53694
It's not safe. It will appear to work in trivial cases, but most likely blow up in strange and spectacular ways under production loads. The correct solution is to write to a new temporary file and then, when complete, rename the temp file to the original file. (this also helps prevent partially written files).
Upvotes: 2