/**
 * Copy a file from args[0] to args[1] using UTF-8 encoding.
 * Open source file and destination file. If the destination file
 * exists, ask the user if it's ok to overwrite it.
 */
import java.util.*;
import java.io.*;

public class UTF8CopyFile
{
    public static final String ENCODING = "UTF-8";
    
    public static void main(String[] args)
    {
        // check that the number of arguments is correct
        if (args.length != 2)
        {
            System.out.println("Usage: java UTF8CopyFile <src> <dest>");
            System.exit(0);
        }
        
        Scanner keyboard = null;
        File destFile = null;
        BufferedReader src = null;
        PrintWriter dest = null;
        String line = "";
        String lineSep = System.getProperty("line.separator"); // get line separator from system
        String answer;
        
        try
        {
            // open the source file for reading
            src = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), ENCODING));
            
            // Create File object for the destination file
            destFile = new File(args[1]);
            
            // if destination file exists and they have permission to write it,
            // ask if it's ok to overwrite it
            if (destFile.exists())
            {
                keyboard = new Scanner(System.in);
                
                System.out.print("File " + args[1] + " exists. " + "Overwrite? (y/n) ");
                answer = keyboard.nextLine();
                
                if ( !answer.equalsIgnoreCase("y"))
                {
                    src.close();
                    System.exit(0);
                }
            }
            
            // open destination for writing - OVERWRITES previous contents
            dest = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile), ENCODING)));  
            
            // open destination for writing - APPENDS TO previous contents
            //dest = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile, true), ENCODING)));  
            
            // read each line and print to output file
            while ((line = src.readLine()) != null)
            {
                dest.write(line + lineSep);
            }
            
            // DON'T FORGET TO CLOSE THE FILES !!!
            src.close();
            dest.close();
        }
        catch (FileNotFoundException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }
}