I expected to find XMLStreamReader
to be AutoCloseable
in Java 7. However, that is not the case. Is there a technical reason why StAX reader/writer interfaces were not (or should not be) retrofitted to implement AutoCloseable
? They already have close methods, whose intent is not different from the close method of AutoCloseable
.

- 225
- 1
- 8
2 Answers
If you look closer to the close()
method of AutoCloseable
:
Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.
Or even Closeable
close()
method :
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
Whereas the close()
method of XMLStreamReader
says :
Frees any resources associated with this Reader. This method does not close the underlying input source.
Indeed the input source is managed by the Reader
which implement the Closeable
interface. So it's the reader that can be close in the try-with-ressource.
For example :
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = null;
try (FileReader fr = new FileReader("file.xml")) { //Will close the FileReader
reader = factory.createXMLStreamReader(fr);
reader.close();
}
catch (XMLStreamException ex) {
if(reader!=null)try {
reader.close();
} catch (XMLStreamException ex1) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex1);
}
}

- 19,951
- 10
- 65
- 112
-
4I would personally restructure that code. reader.close() should be in a finally block in case an exception occurs (your catch is only for XMLStreamException but it could throw an unchecked exception too.) I would also remove the check for reader being null and simply nest a second level of try-finally inside the other try block. – Hakanai Nov 09 '12 at 05:16
There is no technical reason why they couldn't have made these things AutoCloseable
. I figure it just comes down to laziness or insufficient time looking for methods called close().

- 12,010
- 10
- 62
- 132