簡體   English   中英

為什么在使用PrintWriter時數據未寫入文件?

[英]Why data not be written to File when use PrintWriter?

我正在與PrintWriter一起將數據寫入文件,但沒有按預期工作。 程序構建成功,但是數據未輸出到文件。 這是我的代碼:

 File source = new File("notebook.txt");
 PrintWriter out = new PrintWriter(source);
 out.print("I hate Mondays");

當我嘗試使用另一種方式創建PrintWriter對象時,如下所示:

File source = new File("notebook.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(source)));
out.print("I love Fridays");

我不明白PrintWiter構造函數有什么區別。 為什么第一個塊沒有將數據輸出到文件?

您必須刷新PrintWriter才能將數據寫入文件。 您可以either by explicitly call the close method or use the try-with-resource`語句來關閉PrintWriter來實現此目的:

File source = new File("notebook.txt");
try (PrintWriter out = new PrintWriter(source)) {
    out.print("I hate Mondays");
}

或者,您可以不使用try-with-resource語句使用它:

PrintWriter out = new PrintWriter(source);
out.print("I hate Mondays");
out.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM