I know that normally streams
and formatters
(particularly java.util.Formatter
) in Java should be closed in finally
to avoid from resource leaks. But here I am a little bit confused, because I see a lot of examples where people just close it without any finally block, especially the formatters. This question may have no sense to some people, but I want to be sure in what I am asking about.
Some examples from java2s.com and from tutorialspoint.com where the formatters are just closed without any block.
Please consider that my question is only for Java 6 and lower versions, because I know about try with resources.
Example:
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
// format a new string
String name = "from java2s.com";
formatter.format("Hello %s !", name);
// print the formatted string
System.out.println(formatter);
// close the formatter
formatter.close();
// attempt to access the formatter results in exception
System.out.println(formatter);
}
In this specific example, it is not necessary to call close()
. You only need to close the formatter if the underlying appender is Closable
. In this case you are using a StringBuffer
, which is not Closable
so the call to close()
does nothing. If you were to use Writer
or PrintStream
, those are closable and the call to close()
would be necessary to avoid leaving the stream open.
If you are ever unsure if it is Closable
it is best to just call close()
anyway. No harm in doing so.