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

3

5

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.

Kathyrnkati answered 8/7, 2016 at 9:54 Comment(0)
T
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.

Therianthropic answered 8/7, 2016 at 9:56 Comment(1)
Do I need a try catch arround this close ?Kathyrnkati
W
7

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

Walden answered 8/7, 2016 at 10:0 Comment(0)
T
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.

Therianthropic answered 8/7, 2016 at 9:56 Comment(1)
Do I need a try catch arround this close ?Kathyrnkati
E
2

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");
}
Efrainefram answered 8/7, 2016 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.