Java – the xmlstreamreader does not close the open XML file

To use xmlstreamreader, I'm initializing it like –

XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader reader = f.createXMLStreamReader(new FileReader(
        "somefile.xml"));

Iterate it like –

if (reader.hasNext()) {
    reader.next();
    // do something with xml data
}

Finally close it like –

reader.close();

This seems like a normal process, but I see some strange behavior Even after closing the reader, the OS does not allow me to delete / move XML files unless I exit the Java program When running on the win2k8 server, I receive an error message saying Java Exe is using this XML file

So I have a few questions –

>Do I need to explicitly close each FileReader? > How to find the Java code path that keeps this file handle open

Looking at the close () document of xmlstreamreader, I get the following – "release any resources related to this reader. This method will not close the underlying input source."

What does "underlying input source" mean? Why not be closed by readers ()?

Solution

The basic input source mentioned in the document is exactly what you should close Put FileReader in a local variable so that it can be closed:

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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>