4

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.

JavaDev
  • 307
  • 1
  • 3
  • 16

3 Answers3

6

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

Dhaval Simaria
  • 1,886
  • 3
  • 28
  • 36
SCouto
  • 7,808
  • 5
  • 32
  • 49
3

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.

Ajinkya Patil
  • 741
  • 1
  • 6
  • 17
1

Strictly speaking, you should close all three streams. And I would even add a fourth layer, since you probably don’t want to write out the CSV file using the default system encoding, but a customer-specified one. So this is it:

try (FileOutputStream fos = new FileOutputStream(csvFileIn);
     FileWriter fwr = new FileWriter(fos, StandardEncodings.UTF_8);
     BufferedWriter bwr = new BufferedWriter(fwr);
     PrintWriter pwr = new PrintWriter(bwr)) {
  pwr.println("Field1;Field2;Field3");
  pwr.println("Data1;Data2;Data3");
}

In practice, usually only the outermost stream is closed, since it (usually) forwards the close() call to its wrapped stream, and getting an OutOfMemoryError between opening the file and reaching the try block is very unlikely. Then, it looks like this:

try (PrintWriter pwr = new PrintWriter(new BufferedWriter(new FileWriter(new FileOutputStream(csvFileIn), StandardEncodings.UTF_8)))) {
  pwr.println("Field1;Field2;Field3");
  pwr.println("Data1;Data2;Data3");
}
Roland Illig
  • 40,703
  • 10
  • 88
  • 121