Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I need to close when using PrintWriter in Java [duplicate]

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.

like image 880
JavaDev Avatar asked Jan 05 '23 18:01

JavaDev


2 Answers

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

like image 125
SCouto Avatar answered Jan 08 '23 08:01

SCouto


You should use -

fileOut.close();

As you do not have any variable name assigned to BufferedWriter or FileWriter also the fileOut is made from them when you close fileOut it will in turn close both the streams.

like image 38
Ajinkya Patil Avatar answered Jan 08 '23 09:01

Ajinkya Patil