Search code examples
javatexteditorprintwriter

PrintWriter not printing texts to .txt file


This program asks for the output filename and seems to work good. Until I try to open the output file with a text editor or terminal. Then I don't see anything in that file just blank file. This program creates the text file but the file is empty. Thanks for your help in advance.

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();
  }
}

Solution

  • Use out.flush() for flushing the contents to the file.

    Or use auto-flush constructor of PrintWriter (may not be the best performing option) but is anyway an option

    public PrintWriter(Writer out,boolean autoFlush)
    

    autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer