Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try with resources on parameters

Tags:

java

try-catch

this is a stupid question, but I can't figure it out. Do I need to close Object passed as parameters inside a try with resources ?

here it is an example:

StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
    ...
}

Do I need to call

sw.close();

after the try block ? or does it close automatically all the Autocloseable objects passed as parameters ?

like image 984
Fjordo Avatar asked Aug 24 '26 21:08

Fjordo


1 Answers

The implicit invocation of close on your PrintWriter will actually close the underlying Writer as well.

See following example:

StringWriter sw = new StringWriter() {
        @Override
        public void close() throws IOException {
            super.close();
            System.out.println("closed");
        }
};
try (PrintWriter pw = new PrintWriter(sw)) {};

Output

closed
like image 63
Mena Avatar answered Aug 27 '26 16:08

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!