簡體   English   中英

PrintWriter不將文本打印到.txt文件

[英]PrintWriter not printing texts to .txt file

該程序要求輸出文件名,似乎工作正常。 直到我嘗試使用文本編輯器或終端打開輸出文件。 然后我在那個文件中看不到任何空白文件。 此程序創建文本文件但文件為空。 感謝您的幫助。

import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * Writes a Memo file.
 * 
 */
public class MemoPadCreator {
  public static void main(String args[]) {
    Scanner console = new Scanner(System.in);
    System.out.print("Enter Output file name: ");
    String filename = console.nextLine();
  try {
    PrintWriter out = new PrintWriter(filename);

    boolean done = false;
    while (!done) {
      System.out.println("Memo topic (enter -1 to end):");
      String topic = console.nextLine();
      // Once -1 is entered, memo's will no longer be created.
      if (topic.equals("-1")) {
        done = true;
     console.close();
      }
      else {
        System.out.println("Memo text:");
        String message = console.nextLine();

        /* Create the new date object and obtain a dateStamp */
        Date now = new Date();
        String dateStamp = now.toString();

        out.println(topic + "\n" + dateStamp + "\n" + message);
      }
   }
    /* Close the output file */

  } catch (IOException exception) {
    System.out.println("Error processing the file:" + exception);
  }console.close();
  }
}

使用out.flush()將內容刷新到文件中。

或者使用PrintWriter的自動刷新構造函數( 可能不是最佳性能選項 ),但無論如何都是一個選項

public PrintWriter(Writer out,boolean autoFlush)

autoFlush - 布爾值; 如果為true ,則printlnprintf或format方法將刷新輸出緩沖區

您尚未關閉PrintWriter對象。 您需要關閉流以在控制台或文件上反映它(取決於您的outputStream)

out.close();

即使你有

PrintWriter out = new PrintWriter(System.out);
...
...
...
out.close();

然后你需要關閉它,以便輸出寫在控制台上。
因此,在您關閉流的情況下,將寫入文件。

您需要刷新PrintWriter以從內存緩沖區中將要寫入文件的內容。

out.flush();

在任何情況下,您還應始終關閉(釋放)資源,否則鎖定可以或將保留在文件中,具體取決於操作系統。 close()也會自動刷新更改。

暫無
暫無

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

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