2021-03-15

jbanana: Badly drawn banana (Default)
[personal profile] jbanana2021-03-15 05:49 pm

Try-with-reources

You've been able to can auto-close a closable thing for ages now.
try(Reader r = new FileReader(/*blah*/)){
   r.whatever();
}
// r is automatically closed
But today I found that it works for something you already opened!
Reader r = new FileReader(/*blah*/);
try(r){
   r.whatever();
}
// r is automatically closed
This came up because I had a list of files and I wanted to close each one after handling it. So I couldn't create it in the header of the try block.