简体   繁体   中英

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

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

You haven't close your PrintWriter object. You need to close the stream to reflect it on console or file (depending upon your outputStream)

out.close();

Even if you have

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

Then you need to close it so the output is written on console.
So in your case closing the stream will write to the file.

You need to flush the PrintWriter for the contents to be written into the file from memory buffer.

out.flush();

In any case you should also always close (release) the resources, as otherwise locks can or will remain on the file, depending on the OS. And close() also flushes the changes automatically.

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