Java trick: Use an implicit "finally" block to automatically close a stream

In Java 7, an implicit finally block will automatically close an output stream. Meaning that, instead of all this:

PrintWriter writer = new PrintWriter(targetFile, "UTF-8");
try{
    writer.write("Hello World");
    writer.close();
} catch(FileNotFoundException | UnsupportedEncodingException e){
    // Handle exception
}

You really only need this:

try(PrintWriter writer = new PrintWriter(targetFile, "UTF-8")){
    writer.write("Hello World");
} catch(FileNotFoundException | UnsupportedEncodingException e) { 
    // Handle exception 
}

The implicit finally block will automatically close the output stream.

Written on October 24, 2014