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");
}