简体   繁体   中英

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?

You have to flush the PrintWriter in order to write the data to the file. You can reach this by closing the PrintWriter either by explicitly call the close method or use the try-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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM