Assuming the file path referenced in the following class is accessible and able to be written, what is the output of the following program?
package mypkg; /*from w w w. j a va 2s . c o m*/ import java.io.*; public class Main { public final static void main(String... inventory) throws Exception { Writer w = new FileWriter("data.txt"); try (BufferedWriter bw = new BufferedWriter(w)) { bw.write("test!"); } finally { w.flush(); w.close(); } System.out.print("Done!"); } }
D.
The code compiles without issue, making Options B and C incorrect.
The BufferedWriter uses the existing FileWriter object as the low-level stream to write the file to disk.
By using the try-with-resources block, though, the BufferedWriter calls close()
before executing any associated catch or finally blocks.
Since closing a high-level stream automatically closes the associated low-level stream, the w object is already closed by the time the finally block is executed.
The flush()
command triggers an IOException at runtime, making Option D the correct answer.