//  PWriter.java - How to create and write a file using a PrintWriter

import java.io.*;
import javax.swing.JOptionPane;

public class PWriter {

    /**
     *  File name (possibly including full path)
     */
    private final String FILE_NAME = "PWriter.txt";
    private final String NL = System.getProperty("line.separator");
    private PrintWriter pw;

    /**
     *  Attempt to create and write a "text file" using a PrintWriter
     */
    PWriter() {
        System.out.println("\nDemonstrate use of PrintWriter\n");
        if (createPW()) {
            pw.println("This is written to " + FILE_NAME);
            for (int i = 0; i < 10; i++) {
                pw.printf("%3d  %7.4f%s", i, Math.sqrt(i), NL);  // cannot use \n; use NL instead
            }
            pw.println("===============================");
            pw.close();                                          // must remember to call close() !
        } else
            System.out.println("Attempted create/write of " + FILE_NAME + " has failed\n");
        System.out.println("End of Demo\n");
    }

    /**
     *  Create a PrintWriter, create/open file for appending
     */
    public boolean createPW() {
        boolean returnCode = true;
        try {                                                    // true for 'append'
            pw = new PrintWriter(new BufferedWriter(new FileWriter(FILE_NAME, true)));
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, 
                                    "Cannot create/write file: " + FILE_NAME, 
                                    "File create/write failure", JOptionPane.ERROR_MESSAGE); 
            pw = null;
            returnCode = false;
        }
        return returnCode;
    }

    /**
     *  Close the PrintWriter file
     */
    public void closePW() {
        if (pw != null)
            pw.close();
    }

    /**
     *  Run the PrintWriter demo
     */
    public static void main(String[] args) {
        new PWriter();
    }

} // end class PWriter
