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

2 java text editor printwriter

该程序要求输出文件名,似乎工作正常.直到我尝试使用文本编辑器或终端打开输出文件.然后我在那个文件中看不到任何空白文件.此程序创建文本文件但文件为空.感谢您的帮助.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Nar*_*hai 5

使用out.flush()冲洗内容的文件.

或者使用PrintWriter的自动刷新构造函数(可能不是最佳性能选项),但无论如何都是一个选项

public PrintWriter(Writer out,boolean autoFlush)
Run Code Online (Sandbox Code Playgroud)

autoFlush - 布尔值; if true,the println,printf或format方法将刷新输出缓冲区