Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLStreamReader not closing opened xml file

Tags:

java

stream

xml

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 -

  1. Do I need to explicitly close each FileReader's close?
  2. How can I find out which java code path is keeping this file handle open.

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()?

like image 577
siddharth178 Avatar asked May 07 '11 12:05

siddharth178


1 Answers

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
like image 119
jabal Avatar answered Oct 02 '22 19:10

jabal