This means that InputStreamReader never closes.
A? In your code, this is ... And that will certainly handle the .close () of your resource stream. See below for more details.
As @SotiriosDelimanolis mentions , however, you can declare more than one resource in the "resource block" of the try-with-resources statement.
You have one more problem: .getResourceAsStream() may return null; therefore you may have NPE.
I would do it if I were you:
final URL url = ModelCodeGenerator.class.getClassLoader() .getResource("/model.java.txt"); if (url == null) throw new IOException("resource not found"); try ( final InputStream in = url.openStream(); final Reader reader = new InputStreamReader(in, someCharsetOrDecoder); ) {
There is a very important point to consider , however ...
Closeable extends AutoCloseable , yes; in fact, it differs only in “signature wise”, with the exception of the abandoned ones ( IOException vs Exception ). But there is a fundamental difference in behavior.
From javadoc AutoCloseable .close() (my attention):
Note: unlike the Closeable Closeable method, this closure method is not required idempotent. In other words, calling this close method several times may have some visible side effect, unlike Closeable.close, which should not have an effect when called more than once . However, developers of this interface are strongly encouraged to use their close methods idempotent.
And indeed, javadoc Closeable makes this clear:
Closes this thread and frees the associated system resources. If the thread is already closed, calling this method has no effect.
You have two very important points:
- By contract, a
Closeable also takes care of all resources associated with it; therefore, if you close the BufferedReader , which wraps the Reader , which wraps the InputStream , all three close; - If you call
.close() more than once, there will be no additional effect.
It also means, of course, that you can select the paranoid parameter and keep the link to all Closeable resources and close all of them; but if you have AutoCloseable resources in the mix that are not Closeable !