/**
 * Write 3 lines of utf8 text to file specified by args[0].
 * Ask user before overwriting if file exists.
 */
import java.io.*;
import java.util.*;

public class UTF8FileOutputDemo
{
    public static final String ENCODING = "UTF-8";
    
    public static void main(String[] args)
    {
        
        // make sure number of arguments is correct
        if (args.length != 1)
        {
            System.out.println("Usage: java UTF8FileOutputDemo <filename>");
            System.exit(0);
        }
        
        String fileName = args[0];
        File destFile = new File(fileName);
        String line;
        PrintWriter dest = null;
        Scanner keyboard = new Scanner(System.in, ENCODING);
        String answer;

        // if file exists, ask before overwriting
        if (destFile.exists())
        {
            System.out.print(destFile.getAbsolutePath() + " exists. Overwrite? (y/n): ");
            answer = keyboard.nextLine();
            
            // exit program if they don't want to overwrite
            if ( !answer.equalsIgnoreCase("y"))
            {
                System.exit(0);
            }
        }
        
        try
        {
            // open file for writing, utf8
            dest = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), ENCODING)));  
            
            // ask user to enter 3 lines of text and write them to the output file
            System.out.println("Enter three lines of text to be written to " + fileName + " :");
            for (int count = 1; count <= 3; count++)
            {
                line = keyboard.nextLine();
                dest.println(line);
            }
            
            // don't forget to close the file
            dest.close( );
            System.out.println("Those lines were written to " +  fileName);
        }
        catch(UnsupportedEncodingException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        catch(FileNotFoundException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }
}