What do I need to close when using PrintWriter in Java

JavaDev picture JavaDev · Jul 8, 2016 · Viewed 7.6k times · Source

When using a PrintWriter like this :

PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(csvFileIn)));

What do I need to close in the finally block ? The PrintWriter, the BufferedWriter and the FileWriter ?

Do I need to try catch the close statement in the finally block ?

[EDIT] I need to use java 6, so I can't use the try-with-resources statement.

Answer

SCouto picture SCouto · Jul 8, 2016

You can use a try-with-resources block

try (PrintWriter fileOut = new PrintWriter(new BufferedWriter(new     FileWriter(csvFileIn)))) {
    //WHATEVER you need to do
}

Since PrintWriter implements AutoCloseable it will close by itself once the try block is complete (even if an exception is raised)

Check more info about this here