To use XMLStreamReader I am initializing it like -
XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader reader = f.createXMLStreamReader(new FileReader(
"somefile.xml"));
Iterating over it like -
if (reader.hasNext()) {
reader.next();
// do something with xml data
}
Finally closing it like -
reader.close();
This looks to be a normal flow but I am seeing some strange behavior. Even after closing reader, OS doesn't allow me delete/move the xml file unless I exit from java program. When run on Win2k8-server, I get error message saying java.exe is using this xml file.
So I have couple of questions -
Looking @ the documentation of XMLStreamReader's close(), I get following - "Frees any resources associated with this Reader. This method does not close the underlying input source."
What is the meaning of "underlying input source"? Why is that not closed by reader's close()?
The underlying input source mentioned in the doc is exactly what you should close. Put the FileReader into a local variable to be able to close it:
XMLInputFactory f = XMLInputFactory.newInstance();
FileReader fr = new FileReader("somefile.xml");
XMLStreamReader reader = f.createXMLStreamReader(fr);
// process xml
reader.close();
fr.close();
//suggest using apache commons IOUtils.closeQuietly(fr); this way you
// don't have to deal with exceptions if you don't want
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With