/**
 * Demonstration of writing from an array to a file using a FileWriter object.  Also includes exception handling.
 * @author Hyrum D. Carroll
 * @version 0.1 (October 24, 2019)
 */

import java.util.Scanner;
import java.io.FileWriter;
import java.io.Writer;
import java.io.IOException;

public class FileWriterExample {

    /**
     * Close a Writer object (if it's valid)
     * @param file Reference to a file (or null) 
     */
    public static void closeWriter( Writer file ){
        // close() can throw an exception
        try{
            if( file != null ){
                System.out.println("Reference is valid, so (attempting to) close the file...");
                file.close(); // close() can throw IOException
            }
        }catch( IOException e ){
            System.out.println("ERROR: IOException when attempting to close the file: " + e.getMessage() );
        }
    }


   public static void main(String[] args) {
       Scanner stdinScanner = new Scanner( System.in );  // for user input (from the keyboard)
       String userInput;  // What the user inputted (and what will be written to the file)
       String filename;  // Output filename
       FileWriter out = null; // Output file stream

       // Get user input (a joke)
       System.out.print("Please enter a joke: ");
       userInput = stdinScanner.nextLine();
       // System.out.print( "joke: " + userInput);

       // Get where to write the user input
       System.out.print("Please enter where a filename (of where to save your joke): ");
       filename = stdinScanner.next();

       try{
           out = new FileWriter( filename ); // Can throw IOException

           // Write one character at a time
           for( int i = 0; i < userInput.length(); ++i ){
               char ch = userInput.charAt(i);
               System.out.println("Writing " + ch + ".");
               out.write( ch );
           }
           out.write( '\n' );

       }catch( IOException e ){
           System.out.println( "IOException: " + e.getMessage() );
       }finally{
           closeWriter( out );
       }
   }
}