Search code examples
javatry-catchfilewriterprintwriterbufferedwriter

What do I need to close when using PrintWriter in Java


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.


Solution

  • 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.