XMLStreamReader does not close open XML file

To use XMLStreamReader, I initialize it as -

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

Iterate over it like -

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

Finally closing it like -

 reader.close(); 

This looks like a normal flow, but I see strange behavior. Even after closing the read, the OS does not allow me to delete / move the xml file unless I exit the java program. When starting up on the Win2k8 server, an error message appears: java.exe uses this XML file.

So, I have a couple of questions -

  • Do I need to explicitly close each FileReader file?
  • How to find out which java code path this file descriptor supports.

Looking at the XMLStreamReader documentation close (), I get the following: "Releases any resources associated with this Reader. This method does not close the underlying input source."

What is the meaning of the "main input source"? Why is this not closed by the reader close ()?

+6
source share
2 answers

The main input source mentioned in the document is exactly what you should close. Place FileReader in a local variable 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 
+9
source

What is the meaning of the "main input source"? Why is this not closed by the reader close ()?

You created an XMLReader using XMLInputFactory.createXMLStreamReader with an InputStream argument or so. This is the "main input source." :) Because it is open outside of XMLReader, so XMLReader does not close it. But, if you need to, you can use this wrapper class for XMLReader. It just works.

 import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.StreamReaderDelegate; public class XMLFileReader extends StreamReaderDelegate implements AutoCloseable { private final static XMLInputFactory factory = XMLInputFactory.newFactory(); private final Path file; private final InputStream stream; private final XMLStreamReader reader; public XMLFileReader(Path file) throws IOException, XMLStreamException { super(); this.file = file; stream = Files.newInputStream(this.file); reader = factory.createXMLStreamReader(stream); setParent(reader); } @Override public void close() throws XMLStreamException { try { super.close(); stream.close(); } catch (IOException e) { throw new XMLStreamException(file+" : "+e.getMessage(),e); } } } 
+1
source

Source: https://habr.com/ru/post/887512/


All Articles