Q:

Why data not be written to File when use PrintWriter?

I am working with PrintWriter to write data to a file but it did not work as I expected. Program is built successfully but data didn't output to file. Here is my code:
 File source = new File("notebook.txt");
 PrintWriter out = new PrintWriter(source);
 out.print("I hate Mondays");

And when I try to use another way to create PrintWriter object as below it works:
File source = new File("notebook.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(source)));
out.print("I love Fridays");

I don't understand what is the difference in constructor of PrintWiter. Why didn't the first block output data to the file? 

A:

You have to flush the PrintWriter in order to write the data to the file.  You can reach this by closing the PrintWritereither by explicitly call theclosemethod or use thetry-with-resource` statement:
File source = new File("notebook.txt");
try (PrintWriter out = new PrintWriter(source)) {
    out.print("I hate Mondays");
}

Alternativly you can use it without the try-with-resource statement:
PrintWriter out = new PrintWriter(source);
out.print("I hate Mondays");
out.close();

